text:
// Copyright (c) Aurora Studio. All rights reserved.
//
// Licensed under the MIT License. See LICENSE in the project root for license information.
using AudioVisualizer;
using Aurora.Music.Controls;
using Aurora.Music.Core;
using Aurora.Music.Core.Models;
using Aurora.Music.Core.Models.Json;
using Aurora.Music.PlaybackEngine;
using Aurora.Shared.Extensions;
using Aurora.Shared.Helpers;
using Aurora.Shared.MVVM;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using Windows.ApplicationModel.Core;
using Windows.UI;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;

namespace Aurora.Music.ViewModels
{
    enum ReportType
    {
        bye, end, @new, playing, skip, rate, unrate
    }
    class DoubanPageViewModel : ViewModelBase
    {
        Queue<string> playedQueue = new Queue<string>();

        public ObservableCollection<ChannelGroup> Channels { get; set; }
        private Uri artwork;
        public Uri Artwork
        {
            get { return artwork; }
            set { SetProperty(ref artwork, value); }
        }

        public bool NightModeEnabled { get; set; } = Settings.Current.NightMode;

        private string sid;
        private string title;
        public string Title
        {
            get { return title; }
            set { SetProperty(ref title, value); }
        }

        private List<Color> palette;
        public List<Color> Palette
        {
            get { return palette; }
            set { SetProperty(ref palette, value); }
        }

        private bool rateToggle;
        public bool RateToggle
        {
            get { return rateToggle; }
            set
            {
                Task.Run(async () =>
                {
                    var list = await Report(value ? ReportType.rate : ReportType.unrate, channel.ToString(), sid);
                    if (list.r == 0)
                    {
                        await PlaybackEngine.PlaybackEngine.Current.AddtoNextPlay(list.song.Select(a => new Core.Models.Song()
                        {
                            Title = a.title,
                            Album = a.albumtitle,
                            OnlineUri = new Uri(a.url),
                            OnlineID = a.sid,
                            IsOnline = true,
                            PicturePath = a.picture,
                            Performers = a.singers.Select(s => s.name).ToArray(),
                            AlbumArtists = new string[] { a.artist },
                        }).ToList());

                        PlaybackEngine.PlaybackEngine.Current.Play();
                    }
                });

                SetProperty(ref rateToggle, value);
            }
        }

        private string description;
        public string Description
        {
            get { return description; }
            set { SetProperty(ref description, value); }
        }

        public DoubanPageViewModel()
        {
            Channels = new ObservableCollection<ChannelGroup>();

            Task.Run(async () =>
            {
                await Init();
            });
        }

        internal void Detach()
        {
            PlaybackEngine.PlaybackEngine.Current.ItemsChanged -= Current_StatusChanged;
            PlaybackEngine.PlaybackEngine.Current.PositionUpdated -= Current_PositionUpdated;
            PlaybackEngine.PlaybackEngine.Current.PlaybackStatusChanged -= Current_PlaybackStatusChanged;
            Palette?.Clear();
            Palette = null;
            Channels?.Clear();
            Channels = null;
        }

        private double olume = Settings.Current.PlayerVolume;
        public double Volume
        {
            get { return olume; }
            set
            {
                SetProperty(ref olume, value);
                Settings.Current.PlayerVolume = value;
                PlaybackEngine.PlaybackEngine.Current.ChangeVolume(value);
            }
        }

        public string VolumeToSymbol(double d)
        {
            if (d.AlmostEqualTo(0))
            {
                return "\uE198";
            }
            if (d < 33.333333)
            {
                return "\uE993";
            }
            if (d < 66.66666667)
            {
                return "\uE994";
            }
            return "\uE995";
        }

        public string VolumeToString(double d)
        {
            return d.ToString("0");
        }

        public DelegateCommand Delete
        {
            get => new DelegateCommand(async () =>
            {
                var list = await Report(ReportType.bye, channel.ToString(), sid);
                if (list.r == 0)
                {
                    await PlaybackEngine.PlaybackEngine.Current.NewPlayList(list.song.Select(a => new Core.Models.Song()
                    {
                        Title = a.title,
                        Album = a.albumtitle,
                        OnlineUri = new Uri(a.url),
                        OnlineID = a.sid,
                        IsOnline = true,
                        PicturePath = a.picture,
                        Performers = a.singers.Select(s => s.name).ToArray(),
                        AlbumArtists = new string[] { a.artist },
                    }).ToList());

                    PlaybackEngine.PlaybackEngine.Current.Play();
                }
                else
                {
                    MainPage.Current.PopMessage($"Playing error: {list.err}");
                }
            });
        }

        public DelegateCommand Next
        {
            get => new DelegateCommand(async () =>
            {
                PlaybackEngine.PlaybackEngine.Current?.Next();
                if (lastProgress < 0.9)
                {
                    var list = await Report(ReportType.skip, channel.ToString(), sid);
                    if (list.r == 0)
                    {
                        await PlaybackEngine.PlaybackEngine.Current.AddtoNextPlay(list.song.Select(a => new Core.Models.Song()
                        {
                            Title = a.title,
                            Album = a.albumtitle,
                            OnlineUri = new Uri(a.url),
                            OnlineID = a.sid,
                            IsOnline = true,
                            PicturePath = a.picture,
                            Performers = a.singers.Select(s => s.name).ToArray(),
                            AlbumArtists = new string[] { a.artist },
                        }).ToList());
                        if (PlaybackEngine.PlaybackEngine.Current?.IsPlaying == null || !(bool)PlaybackEngine.PlaybackEngine.Current?.IsPlaying)
                        {
                            PlaybackEngine.PlaybackEngine.Current?.Play();
                        }
                    }
                }

            });
        }

        async Task<playlist> Report(ReportType type, string channel, string sid = null)
        {
            var args = new Dictionary<string, string>()
            {
                ["channel"] = channel,
                ["from"] = "mainsite",
                ["pt"] = "0.0",
                ["kbps"] = "128",
                ["formats"] = "aac",
                ["alt"] = "json",
                ["app_name"] = "radio_iphone",
                ["apikey"] = "02646d3fb69a52ff072d47bf23cef8fd",
                ["client"] = "s:mobile|y:iOS 10.2|f:115|d:b88146214e19b8a8244c9bc0e2789da68955234d|e:iPhone7,1|m:appstore",
                ["client_id"] = "02646d3fb69a52ff072d47bf23cef8fd",
                ["icon_cate"] = "xlarge",
                ["udid"] = "b88146214e19b8a8244c9bc0e2789da68955234d",
                ["douban_udid"] = "b635779c65b816b13b330b68921c0f8edc049590",
                ["version"] = "100",
                //["type"] = "n"
            };

            switch (type)
            {
                case ReportType.bye:
                    args.Add("type", "b");
                    if (sid == null)
                        throw new ArgumentException("sid is null");
                    args.Add("sid", sid);
                    break;
                case ReportType.end:
                    args.Add("type", "e");
                    if (sid == null)
                        throw new ArgumentException("sid is null");
                    args.Add("sid", sid);
                    break;
                case ReportType.@new:
                    args.Add("type", "n");
                    break;
                case ReportType.playing:
                    args.Add("type", "p");
                    break;
                case ReportType.skip:
                    args.Add("type", "s");
                    if (sid == null)
                        throw new ArgumentException("sid is null");
                    args.Add("sid", sid);
                    break;
                case ReportType.rate:
                    args.Add("type", "r");
                    if (sid == null)
                        throw new ArgumentException("sid is null");
                    args.Add("sid", sid);
                    break;
                case ReportType.unrate:
                    args.Add("type", "u");
                    if (sid == null)
                        throw new ArgumentException("sid is null");
                    args.Add("sid", sid);
                    break;
                default:
                    throw new ArgumentException("ReportType mismatch");
            }

            string h = string.Empty;

            while (playedQueue.TryDequeue(out string songID))
            {
                h += $"sid:{songID}|";
            }
            if (!h.IsNullorEmpty())
            {
                h.Remove(h.Length - 1);
                args.Add("h", h);
            }

            Dictionary<string, string> addHeader = null;

            if (Settings.Current.VerifyDoubanLogin())
            {
                addHeader = new Dictionary<string, string>()
                {
                    ["Authorization"] = $"Bearer {Settings.Current.DoubanToken}"
                };
                args.Add("user_id", Settings.Current.DoubanUserID);
                args.Add("expire", Settings.Current.DoubanExpireTime.ToString("0"));
                args.Add("token", Settings.Current.DoubanToken);
            }

            var json = await ApiRequestHelper.HttpGet("https://api.douban.com/v2/fm/playlist", args, addHeader, true);
            if (!json.IsNullorEmpty())
            {
                return JsonConvert.DeserializeObject<playlist>(json);
            }
            return null;
        }

        public DelegateCommand PlayPause
        {
            get
            {
                return new DelegateCommand(() =>
                {
                    if (sid == null)
                    {
                        Switch(Channels.First().First());
                        return;
                    }
                    if (IsPlaying is bool b)
                    {
                        if (b)
                        {
                            PlaybackEngine.PlaybackEngine.Current?.Pause();
                        }
                        else
                        {
                            PlaybackEngine.PlaybackEngine.Current?.Play();
                        }
                    }
                    else
                    {
                        PlaybackEngine.PlaybackEngine.Current?.Play();
                    }
                });
            }
        }

        private bool? isPlaying;
        private int channel;
        private double lastProgress;

        public bool? IsPlaying
        {
            get { return isPlaying; }
            set { SetProperty(ref isPlaying, value); }
        }

        private CustomVisualizer isualizer;
        public CustomVisualizer Visualizer
        {
            get => isualizer;
            set
            {
                isualizer = value;
                MainPageViewModel.Current.VisualizerSource.SourceChanged += VisualizerSource_SourceChanged;
                if (MainPageViewModel.Current.VisualizerSource.Source != null)
                {
                    isualizer.Source = MainPageViewModel.Current.VisualizerSource.Source;
                }
            }
        }

        private void VisualizerSource_SourceChanged(object sender, IVisualizationSource args)
        {
            if (isualizer != null)
                isualizer.Source = MainPageViewModel.Current.VisualizerSource.Source;
        }

        public Symbol NullableBoolToSymbol(bool? b)
        {
            if (b is bool bb)
            {
                return bb ? Symbol.Pause : Symbol.Play;
            }
            return Symbol.Play;
        }

        public string NullableBoolToString(bool? b)
        {
            if (b is bool bb)
            {
                return bb ? Consts.Localizer.GetString("PauseText") : Consts.Localizer.GetString("PlayText");
            }
            return Consts.Localizer.GetString("PlayText");
        }

        public async Task Init()
        {
            var result = await ApiRequestHelper.HttpGet("https://api.douban.com/v2/fm/app_channels?alt=json&apikey=02646d3fb69a52ff072d47bf23cef8fd&app_name=radio_iphone&client=s%3Amobile%7Cy%3AiOS%2010.2%7Cf%3A115%7Cd%3Ab88146214e19b8a8244c9bc0e2789da68955234d%7Ce%3AiPhone7%2C1%7Cm%3Aappstore&douban_udid=b635779c65b816b13b330b68921c0f8edc049590&icon_cate=xlarge&udid=b88146214e19b8a8244c9bc0e2789da68955234d&version=115");
            var douban = JsonConvert.DeserializeObject<Douban>(result);

            PlaybackEngine.PlaybackEngine.Current.ItemsChanged += Current_StatusChanged;
            PlaybackEngine.PlaybackEngine.Current.PlaybackStatusChanged += Current_PlaybackStatusChanged;
            PlaybackEngine.PlaybackEngine.Current.PositionUpdated += Current_PositionUpdated;

            await CoreApplication.MainView.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () =>
            {
                foreach (var item in douban.groups)
                {
                    var g = new ChannelGroup()
                    {
                        Name = (item.group_name.IsNullorEmpty() ? (Settings.Current.VerifyDoubanLogin() ? Settings.Current.DoubanUserName : Consts.Localizer.GetString("NotLogin")) : item.group_name),
                        ID = item.group_id,
                    };
                    foreach (var c in item.chls)
                    {
                        g.Add(new ChannelViewModel()
                        {
                            Cover = new Uri(c.cover),
                            Description = c.intro,
                            Name = c.name,
                            ID = c.id,
                        });
                    }
                    Channels.Add(g);
                }
            });
        }

        private async void Current_PlaybackStatusChanged(object sender, PlaybackStatusChangedArgs e)
        {
            await CoreApplication.MainView.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () =>
            {
                IsPlaying = e.PlaybackStatus == Windows.Media.Playback.MediaPlaybackState.Playing;
                if (e.PlaybackStatus == Windows.Media.Playback.MediaPlaybackState.Playing)
                {
                    MainPageViewModel.Current.IsVisualizing = true;
                }
            });
        }

        private void Current_PositionUpdated(object sender, PositionUpdatedArgs e)
        {
            lastProgress = e.Current / e.Total;
        }

        private async void Current_StatusChanged(object sender, PlayingItemsChangedArgs e)
        {
            await CoreApplication.MainView.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () =>
            {
                if (e.CurrentSong != null)
                {
                    if (e.CurrentSong.OnlineID != sid)
                    {
                        if (lastProgress >= 0.9)
                        {
                            var p = string.Copy(sid);
                            playedQueue.Enqueue(p);
                            Task.Run(async () =>
                            {
                                var list = await Report(ReportType.end, channel.ToString(), p);
                                if (list.r == 0)
                                {
                                    await PlaybackEngine.PlaybackEngine.Current.AddtoNextPlay(list.song.Select(a => new Core.Models.Song()
                                    {
                                        Title = a.title,
                                        Album = a.albumtitle,
                                        OnlineUri = new Uri(a.url),
                                        OnlineID = a.sid,
                                        IsOnline = true,
                                        PicturePath = a.picture,
                                        Performers = a.singers.Select(s => s.name).ToArray(),
                                        AlbumArtists = new string[] { a.artist },
                                    }).ToList());

                                    if (PlaybackEngine.PlaybackEngine.Current?.IsPlaying == null || !(bool)PlaybackEngine.PlaybackEngine.Current?.IsPlaying)
                                    {
                                        PlaybackEngine.PlaybackEngine.Current?.Play();
                                    }
                                }
                            });
                        }

                        Task.Run(async () =>
                        {
                            try
                            {
                                var pal = await ImagingHelper.GetColorPalette(e.CurrentSong.PicturePath.IsNullorEmpty() ? new Uri(Consts.NowPlaceholder) : new Uri(e.CurrentSong.PicturePath));
                                await CoreApplication.MainView.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () =>
                                {
                                    var list = new List<Color>();
                                    for (int i = 0; i < 32; i++)
                                    {
                                        int j = i;
                                        while (j >= pal.Count)
                                        {
                                            j -= pal.Count;
                                        }
                                        list.Add(pal[j]);
                                    }
                                    list.Shuffle();
                                    Palette = list;
                                });
                            }
                            catch (Exception)
                            {
                                var pal = await ImagingHelper.GetColorPalette(new Uri(Consts.NowPlaceholder));
                                await CoreApplication.MainView.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () =>
                                {
                                    var list = new List<Color>();
                                    for (int i = 0; i < 32; i++)
                                    {
                                        int j = i;
                                        while (j >= pal.Count)
                                        {
                                            j -= pal.Count;
                                        }
                                        list.Add(pal[j]);
                                    }
                                    list.Shuffle();
                                    Palette = list;
                                });
                            }

                        });
                        rateToggle = false;
                        RaisePropertyChanged("RateToggle");

                        Title = e.CurrentSong.Title;
                        Description = string.Format(Consts.Localizer.GetString("TileDesc"), e.CurrentSong.Album, string.Join(Consts.CommaSeparator, e.CurrentSong.Performers ?? new string[] { }));
                        Artwork = e.CurrentSong.PicturePath.IsNullorEmpty() ? null : new Uri(e.CurrentSong.PicturePath);
                        sid = e.CurrentSong.OnlineID;

                    }
                }
                else
                {
                    if (IsPlaying is bool aaa && aaa)
                    {
                        Task.Run(async () =>
                        {
                            if (lastProgress >= 0.9)
                            {
                                var p = string.Copy(sid);
                                playedQueue.Enqueue(p);

                                var list = await Report(ReportType.end, channel.ToString(), p);
                                if (list.r == 0)
                                {
                                    await PlaybackEngine.PlaybackEngine.Current.AddtoNextPlay(list.song.Select(a => new Core.Models.Song()
                                    {
                                        Title = a.title,
                                        Album = a.albumtitle,
                                        OnlineUri = new Uri(a.url),
                                        OnlineID = a.sid,
                                        IsOnline = true,
                                        PicturePath = a.picture,
                                        Performers = a.singers.Select(s => s.name).ToArray(),
                                        AlbumArtists = new string[] { a.artist },
                                    }).ToList());

                                    if (PlaybackEngine.PlaybackEngine.Current?.IsPlaying == null || !(bool)PlaybackEngine.PlaybackEngine.Current?.IsPlaying)
                                    {
                                        PlaybackEngine.PlaybackEngine.Current?.Play();
                                    }
                                }

                            }
                            else
                            {
                                var list = await Report(ReportType.skip, channel.ToString(), sid);
                                if (list.r == 0)
                                {
                                    await PlaybackEngine.PlaybackEngine.Current.AddtoNextPlay(list.song.Select(a => new Core.Models.Song()
                                    {
                                        Title = a.title,
                                        Album = a.albumtitle,
                                        OnlineUri = new Uri(a.url),
                                        OnlineID = a.sid,
                                        IsOnline = true,
                                        PicturePath = a.picture,
                                        Performers = a.singers.Select(s => s.name).ToArray(),
                                        AlbumArtists = new string[] { a.artist },
                                    }).ToList());
                                    if (PlaybackEngine.PlaybackEngine.Current?.IsPlaying == null || !(bool)PlaybackEngine.PlaybackEngine.Current?.IsPlaying)
                                    {
                                        PlaybackEngine.PlaybackEngine.Current?.Play();
                                    }
                                }
                            }
                        });
                    }
                    else
                    {
                        MainPageViewModel.Current.IsVisualizing = false;
                    }
                }
            });
        }

        internal async void Switch(ChannelViewModel model)
        {
            if (model.ID == 0)
            {
                if (!Settings.Current.VerifyDoubanLogin())
                {
                    DoubanLogin d = new DoubanLogin();
                    var result = await d.ShowAsync();
                    if (result == ContentDialogResult.Primary)
                    {
                        Channels.Where(a => a.Contains(model)).First().Name = Settings.Current.DoubanUserName;
                    }
                    else
                    {
                        return;
                    }
                }

            }
            channel = model.ID;
            var liat = await Report(ReportType.@new, model.ID.ToString());
            if (liat.r == 0)
            {
                await PlaybackEngine.PlaybackEngine.Current.NewPlayList(liat.song.Select(a => new Core.Models.Song()
                {
                    Title = a.title,
                    Album = a.albumtitle,
                    OnlineUri = new Uri(a.url),
                    OnlineID = a.sid,
                    IsOnline = true,
                    PicturePath = a.picture,
                    Performers = a.singers.Select(s => s.name).ToArray(),
                    AlbumArtists = new string[] { a.artist },
                }).ToList());

                PlaybackEngine.PlaybackEngine.Current.Play();
            }
            else
            {
                MainPage.Current.PopMessage($"Playing error: {liat.err}");
            }
        }
    }
}


text:
<?php

namespace WikiRenderer\Markup\Trac;

/**
 * interface for Trac macro links.
 */
interface MacroInterface
{
    /**
     * @param string $wikiContent
     * @return bool true if the given wiki content is the macro
     */
    public function match($wikiContent);

    /**
     * returns the generator corresponding to the macro.
     *
     * @param Config $config
     * @param \WikiRenderer\Generator\DocumentGeneratorInterface $generator
     * @param string $wikiContent
     * @return \WikiRenderer\Generator\InlineGeneratorInterface
     */
    public function getContent(\WikiRenderer\Markup\Trac\Config $config,
                        \WikiRenderer\Generator\DocumentGeneratorInterface $generator,
                        $wikiContent);
}

redpajama_set_name: RedPajamaGithub


text:
# Rails

## Rails/ActionFilter

Enabled by default | Supports autocorrection
--- | ---
Enabled | Yes

This cop enforces the consistent use of action filter methods.

The cop is configurable and can enforce the use of the older
something_filter methods or the newer something_action methods.

If the TargetRailsVersion is set to less than 4.0, the cop will enforce
the use of filter methods.

### Examples

#### EnforcedStyle: action (default)

```ruby
# bad
after_filter :do_stuff
append_around_filter :do_stuff
skip_after_filter :do_stuff

# good
after_action :do_stuff
append_around_action :do_stuff
skip_after_action :do_stuff
```
#### EnforcedStyle: filter

```ruby
# bad
after_action :do_stuff
append_around_action :do_stuff
skip_after_action :do_stuff

# good
after_filter :do_stuff
append_around_filter :do_stuff
skip_after_filter :do_stuff
```

### Configurable attributes

Name | Default value | Configurable values
--- | --- | ---
EnforcedStyle | `action` | `action`, `filter`
Include | `app/controllers/**/*.rb` | Array

## Rails/ActiveRecordAliases

Enabled by default | Supports autocorrection
--- | ---
Enabled | Yes

Checks that ActiveRecord aliases are not used. The direct method names
are more clear and easier to read.

### Examples

```ruby
#bad
Book.update_attributes!(author: 'Alice')

#good
Book.update!(author: 'Alice')
```

## Rails/ActiveSupportAliases

Enabled by default | Supports autocorrection
--- | ---
Enabled | Yes

This cop checks that ActiveSupport aliases to core ruby methods
are not used.

### Examples

```ruby
# good
'some_string'.start_with?('prefix')
'some_string'.end_with?('suffix')
[1, 2, 'a'] << 'b'
[1, 2, 'a'].unshift('b')

# bad
'some_string'.starts_with?('prefix')
'some_string'.ends_with?('suffix')
[1, 2, 'a'].append('b')
[1, 2, 'a'].prepend('b')
```

## Rails/ApplicationJob

Enabled by default | Supports autocorrection
--- | ---
Enabled | Yes

This cop checks that jobs subclass ApplicationJob with Rails 5.0.

### Examples

```ruby
# good
class Rails5Job < ApplicationJob
  # ...
end

# bad
class Rails4Job < ActiveJob::Base
  # ...
end
```

## Rails/ApplicationRecord

Enabled by default | Supports autocorrection
--- | ---
Enabled | Yes

This cop checks that models subclass ApplicationRecord with Rails 5.0.

### Examples

```ruby
# good
class Rails5Model < ApplicationRecord
  # ...
end

# bad
class Rails4Model < ActiveRecord::Base
  # ...
end
```

## Rails/AssertNot

Enabled by default | Supports autocorrection
--- | ---
Enabled | Yes

Use `assert_not` instead of `assert !`.

### Examples

```ruby
# bad
assert !x

# good
assert_not x
```

### Configurable attributes

Name | Default value | Configurable values
--- | --- | ---
Include | `**/test/**/*` | Array

## Rails/Blank

Enabled by default | Supports autocorrection
--- | ---
Enabled | Yes

This cop checks for code that can be written with simpler conditionals
using `Object#blank?` defined by Active Support.

### Examples

#### NilOrEmpty: true (default)

```ruby
# Converts usages of `nil? || empty?` to `blank?`

# bad
foo.nil? || foo.empty?
foo == nil || foo.empty?

# good
foo.blank?
```
#### NotPresent: true (default)

```ruby
# Converts usages of `!present?` to `blank?`

# bad
!foo.present?

# good
foo.blank?
```
#### UnlessPresent: true (default)

```ruby
# Converts usages of `unless present?` to `if blank?`

# bad
something unless foo.present?

# good
something if foo.blank?

# bad
unless foo.present?
  something
end

# good
if foo.blank?
  something
end
```

### Configurable attributes

Name | Default value | Configurable values
--- | --- | ---
NilOrEmpty | `true` | Boolean
NotPresent | `true` | Boolean
UnlessPresent | `true` | Boolean

## Rails/BulkChangeTable

Enabled by default | Supports autocorrection
--- | ---
Enabled | No

This Cop checks whether alter queries are combinable.
If combinable queries are detected, it suggests to you
to use `change_table` with `bulk: true` instead.
When use this method, make combinable alter queries
a bulk alter query.

The `bulk` option is only supported on the MySQL and
the PostgreSQL (5.2 later) adapter; thus it will
automatically detect an adapter from `development` environment
in `config/database.yml` when the `Database` option is not set.
If the adapter is not `mysql2` or `postgresql`,
this Cop ignores offenses.

### Examples

```ruby
# bad
def change
  add_column :users, :name, :string, null: false
  add_column :users, :nickname, :string

  # ALTER TABLE `users` ADD `name` varchar(255) NOT NULL
  # ALTER TABLE `users` ADD `nickname` varchar(255)
end

# good
def change
  change_table :users, bulk: true do |t|
    t.string :name, null: false
    t.string :nickname
  end

  # ALTER TABLE `users` ADD `name` varchar(255) NOT NULL,
  #                     ADD `nickname` varchar(255)
end
```
```ruby
# bad
def change
  change_table :users do |t|
    t.string :name, null: false
    t.string :nickname
  end
end

# good
def change
  change_table :users, bulk: true do |t|
    t.string :name, null: false
    t.string :nickname
  end
end

# good
# When you don't want to combine alter queries.
def change
  change_table :users, bulk: false do |t|
    t.string :name, null: false
    t.string :nickname
  end
end
```

### Configurable attributes

Name | Default value | Configurable values
--- | --- | ---
Database | `<none>` | `mysql`, `postgresql`
Include | `db/migrate/*.rb` | Array

## Rails/CreateTableWithTimestamps

Enabled by default | Supports autocorrection
--- | ---
Enabled | No

This cop checks the migration for which timestamps are not included
when creating a new table.
In many cases, timestamps are useful information and should be added.

### Examples

```ruby
# bad
create_table :users

# bad
create_table :users do |t|
  t.string :name
  t.string :email
end

# good
create_table :users do |t|
  t.string :name
  t.string :email

  t.timestamps
end

# good
create_table :users do |t|
  t.string :name
  t.string :email

  t.datetime :created_at, default: -> { 'CURRENT_TIMESTAMP' }
end

# good
create_table :users do |t|
  t.string :name
  t.string :email

  t.datetime :updated_at, default: -> { 'CURRENT_TIMESTAMP' }
end
```

### Configurable attributes

Name | Default value | Configurable values
--- | --- | ---
Include | `db/migrate/*.rb` | Array

## Rails/Date

Enabled by default | Supports autocorrection
--- | ---
Enabled | No

This cop checks for the correct use of Date methods,
such as Date.today, Date.current etc.

Using Date.today is dangerous, because it doesn't know anything about
Rails time zone. You must use Time.zone.today instead.

The cop also reports warnings when you are using 'to_time' method,
because it doesn't know about Rails time zone either.

Two styles are supported for this cop. When EnforcedStyle is 'strict'
then the Date methods (today, current, yesterday, tomorrow)
are prohibited and the usage of both 'to_time'
and 'to_time_in_current_zone' is reported as warning.

When EnforcedStyle is 'flexible' then only 'Date.today' is prohibited
and only 'to_time' is reported as warning.

### Examples

#### EnforcedStyle: strict

```ruby
# bad
Date.current
Date.yesterday
Date.today
date.to_time
date.to_time_in_current_zone

# good
Time.zone.today
Time.zone.today - 1.day
```
#### EnforcedStyle: flexible (default)

```ruby
# bad
Date.today
date.to_time

# good
Time.zone.today
Time.zone.today - 1.day
Date.current
Date.yesterday
date.to_time_in_current_zone
```

### Configurable attributes

Name | Default value | Configurable values
--- | --- | ---
EnforcedStyle | `flexible` | `strict`, `flexible`

## Rails/Delegate

Enabled by default | Supports autocorrection
--- | ---
Enabled | Yes

This cop looks for delegations that could have been created
automatically with the `delegate` method.

Safe navigation `&.` is ignored because Rails' `allow_nil`
option checks not just for nil but also delegates if nil
responds to the delegated method.

The `EnforceForPrefixed` option (defaulted to `true`) means that
using the target object as a prefix of the method name
without using the `delegate` method will be a violation.
When set to `false`, this case is legal.

### Examples

```ruby
# bad
def bar
  foo.bar
end

# good
delegate :bar, to: :foo

# good
def bar
  foo&.bar
end

# good
private
def bar
  foo.bar
end

# EnforceForPrefixed: true
# bad
def foo_bar
  foo.bar
end

# good
delegate :bar, to: :foo, prefix: true

# EnforceForPrefixed: false
# good
def foo_bar
  foo.bar
end

# good
delegate :bar, to: :foo, prefix: true
```

### Configurable attributes

Name | Default value | Configurable values
--- | --- | ---
EnforceForPrefixed | `true` | Boolean

## Rails/DelegateAllowBlank

Enabled by default | Supports autocorrection
--- | ---
Enabled | Yes

This cop looks for delegations that pass :allow_blank as an option
instead of :allow_nil. :allow_blank is not a valid option to pass
to ActiveSupport#delegate.

### Examples

```ruby
# bad
delegate :foo, to: :bar, allow_blank: true

# good
delegate :foo, to: :bar, allow_nil: true
```

## Rails/DynamicFindBy

Enabled by default | Supports autocorrection
--- | ---
Enabled | Yes

This cop checks dynamic `find_by_*` methods.
Use `find_by` instead of dynamic method.
See. https://github.com/rubocop-hq/rails-style-guide#find_by

### Examples

```ruby
# bad
User.find_by_name(name)

# bad
User.find_by_name_and_email(name)

# bad
User.find_by_email!(name)

# good
User.find_by(name: name)

# good
User.find_by(name: name, email: email)

# good
User.find_by!(email: email)
```

### Configurable attributes

Name | Default value | Configurable values
--- | --- | ---
Whitelist | `find_by_sql` | Array

### References

* [https://github.com/rubocop-hq/rails-style-guide#find_by](https://github.com/rubocop-hq/rails-style-guide#find_by)

## Rails/EnumUniqueness

Enabled by default | Supports autocorrection
--- | ---
Enabled | No

This cop looks for duplicate values in enum declarations.

### Examples

```ruby
# bad
enum status: { active: 0, archived: 0 }

# good
enum status: { active: 0, archived: 1 }

# bad
enum status: [:active, :archived, :active]

# good
enum status: [:active, :archived]
```

### Configurable attributes

Name | Default value | Configurable values
--- | --- | ---
Include | `app/models/**/*.rb` | Array

## Rails/EnvironmentComparison

Enabled by default | Supports autocorrection
--- | ---
Enabled | Yes

This cop checks that Rails.env is compared using `.production?`-like
methods instead of equality against a string or symbol.

### Examples

```ruby
# bad
Rails.env == 'production'

# bad, always returns false
Rails.env == :test

# good
Rails.env.production?
```

## Rails/Exit

Enabled by default | Supports autocorrection
--- | ---
Enabled | No

This cop enforces that 'exit' calls are not used within a rails app.
Valid options are instead to raise an error, break, return or some
other form of stopping execution of current request.

There are two obvious cases where 'exit' is particularly harmful:

- Usage in library code for your application. Even though rails will
rescue from a SystemExit and continue on, unit testing that library
code will result in specs exiting (potentially silently if exit(0)
is used.)
- Usage in application code outside of the web process could result in
the program exiting, which could result in the code failing to run and
do its job.

### Examples

```ruby
# bad
exit(0)

# good
raise 'a bad error has happened'
```

### Configurable attributes

Name | Default value | Configurable values
--- | --- | ---
Include | `app/**/*.rb`, `config/**/*.rb`, `lib/**/*.rb` | Array
Exclude | `lib/**/*.rake` | Array

## Rails/FilePath

Enabled by default | Supports autocorrection
--- | ---
Enabled | No

This cop is used to identify usages of file path joining process
to use `Rails.root.join` clause. It is used to add uniformity when
joining paths.

### Examples

#### EnforcedStyle: arguments (default)

```ruby
# bad
Rails.root.join('app/models/goober')
File.join(Rails.root, 'app/models/goober')
"#{Rails.root}/app/models/goober"

# good
Rails.root.join('app', 'models', 'goober')
```
#### EnforcedStyle: slashes

```ruby
# bad
Rails.root.join('app', 'models', 'goober')
File.join(Rails.root, 'app/models/goober')
"#{Rails.root}/app/models/goober"

# good
Rails.root.join('app/models/goober')
```

### Configurable attributes

Name | Default value | Configurable values
--- | --- | ---
EnforcedStyle | `arguments` | `slashes`, `arguments`

## Rails/FindBy

Enabled by default | Supports autocorrection
--- | ---
Enabled | Yes

This cop is used to identify usages of `where.first` and
change them to use `find_by` instead.

### Examples

```ruby
# bad
User.where(name: 'Bruce').first
User.where(name: 'Bruce').take

# good
User.find_by(name: 'Bruce')
```

### Configurable attributes

Name | Default value | Configurable values
--- | --- | ---
Include | `app/models/**/*.rb` | Array

### References

* [https://github.com/rubocop-hq/rails-style-guide#find_by](https://github.com/rubocop-hq/rails-style-guide#find_by)

## Rails/FindEach

Enabled by default | Supports autocorrection
--- | ---
Enabled | Yes

This cop is used to identify usages of `all.each` and
change them to use `all.find_each` instead.

### Examples

```ruby
# bad
User.all.each

# good
User.all.find_each
```

### Configurable attributes

Name | Default value | Configurable values
--- | --- | ---
Include | `app/models/**/*.rb` | Array

### References

* [https://github.com/rubocop-hq/rails-style-guide#find-each](https://github.com/rubocop-hq/rails-style-guide#find-each)

## Rails/HasAndBelongsToMany

Enabled by default | Supports autocorrection
--- | ---
Enabled | No

This cop checks for the use of the has_and_belongs_to_many macro.

### Examples

```ruby
# bad
# has_and_belongs_to_many :ingredients

# good
# has_many :ingredients, through: :recipe_ingredients
```

### Configurable attributes

Name | Default value | Configurable values
--- | --- | ---
Include | `app/models/**/*.rb` | Array

### References

* [https://github.com/rubocop-hq/rails-style-guide#has-many-through](https://github.com/rubocop-hq/rails-style-guide#has-many-through)

## Rails/HasManyOrHasOneDependent

Enabled by default | Supports autocorrection
--- | ---
Enabled | No

This cop looks for `has_many` or `has_one` associations that don't
specify a `:dependent` option.
It doesn't register an offense if `:through` option was specified.

### Examples

```ruby
# bad
class User < ActiveRecord::Base
  has_many :comments
  has_one :avatar
end

# good
class User < ActiveRecord::Base
  has_many :comments, dependent: :restrict_with_exception
  has_one :avatar, dependent: :destroy
  has_many :patients, through: :appointments
end
```

### Configurable attributes

Name | Default value | Configurable values
--- | --- | ---
Include | `app/models/**/*.rb` | Array

### References

* [https://github.com/rubocop-hq/rails-style-guide#has_many-has_one-dependent-option](https://github.com/rubocop-hq/rails-style-guide#has_many-has_one-dependent-option)

## Rails/HttpPositionalArguments

Enabled by default | Supports autocorrection
--- | ---
Enabled | Yes

This cop is used to identify usages of http methods like `get`, `post`,
`put`, `patch` without the usage of keyword arguments in your tests and
change them to use keyword args.  This cop only applies to Rails >= 5 .
If you are running Rails < 5 you should disable the
Rails/HttpPositionalArguments cop or set your TargetRailsVersion in your
.rubocop.yml file to 4.0, etc.

### Examples

```ruby
# bad
get :new, { user_id: 1}

# good
get :new, params: { user_id: 1 }
```

### Configurable attributes

Name | Default value | Configurable values
--- | --- | ---
Include | `spec/**/*`, `test/**/*` | Array

## Rails/HttpStatus

Enabled by default | Supports autocorrection
--- | ---
Enabled | Yes

Enforces use of symbolic or numeric value to define HTTP status.

### Examples

#### EnforcedStyle: symbolic (default)

```ruby
# bad
render :foo, status: 200
render json: { foo: 'bar' }, status: 200
render plain: 'foo/bar', status: 304
redirect_to root_url, status: 301

# good
render :foo, status: :ok
render json: { foo: 'bar' }, status: :ok
render plain: 'foo/bar', status: :not_modified
redirect_to root_url, status: :moved_permanently
```
#### EnforcedStyle: numeric

```ruby
# bad
render :foo, status: :ok
render json: { foo: 'bar' }, status: :not_found
render plain: 'foo/bar', status: :not_modified
redirect_to root_url, status: :moved_permanently

# good
render :foo, status: 200
render json: { foo: 'bar' }, status: 404
render plain: 'foo/bar', status: 304
redirect_to root_url, status: 301
```

### Configurable attributes

Name | Default value | Configurable values
--- | --- | ---
EnforcedStyle | `symbolic` | `numeric`, `symbolic`

## Rails/InverseOf

Enabled by default | Supports autocorrection
--- | ---
Enabled | No

This cop looks for has_(one|many) and belongs_to associations where
Active Record can't automatically determine the inverse association
because of a scope or the options used. Using the blog with order scope
example below, traversing the a Blog's association in both directions
with `blog.posts.first.blog` would cause the `blog` to be loaded from
the database twice.

`:inverse_of` must be manually specified for Active Record to use the
associated object in memory, or set to `false` to opt-out. Note that
setting `nil` does not stop Active Record from trying to determine the
inverse automatically, and is not considered a valid value for this.

### Examples

```ruby
# good
class Blog < ApplicationRecord
  has_many :posts
end

class Post < ApplicationRecord
  belongs_to :blog
end
```
```ruby
# bad
class Blog < ApplicationRecord
  has_many :posts, -> { order(published_at: :desc) }
end

class Post < ApplicationRecord
  belongs_to :blog
end

# good
class Blog < ApplicationRecord
  has_many(:posts,
    -> { order(published_at: :desc) },
    inverse_of: :blog
  )
end

class Post < ApplicationRecord
  belongs_to :blog
end

# good
class Blog < ApplicationRecord
  with_options inverse_of: :blog do
    has_many :posts, -> { order(published_at: :desc) }
  end
end

class Post < ApplicationRecord
  belongs_to :blog
end

# good
# When you don't want to use the inverse association.
class Blog < ApplicationRecord
  has_many(:posts,
    -> { order(published_at: :desc) },
    inverse_of: false
  )
end
```
```ruby
# bad
class Picture < ApplicationRecord
  belongs_to :imageable, polymorphic: true
end

class Employee < ApplicationRecord
  has_many :pictures, as: :imageable
end

class Product < ApplicationRecord
  has_many :pictures, as: :imageable
end

# good
class Picture < ApplicationRecord
  belongs_to :imageable, polymorphic: true
end

class Employee < ApplicationRecord
  has_many :pictures, as: :imageable, inverse_of: :imageable
end

class Product < ApplicationRecord
  has_many :pictures, as: :imageable, inverse_of: :imageable
end
```
```ruby
# bad
# However, RuboCop can not detect this pattern...
class Physician < ApplicationRecord
  has_many :appointments
  has_many :patients, through: :appointments
end

class Appointment < ApplicationRecord
  belongs_to :physician
  belongs_to :patient
end

class Patient < ApplicationRecord
  has_many :appointments
  has_many :physicians, through: :appointments
end

# good
class Physician < ApplicationRecord
  has_many :appointments
  has_many :patients, through: :appointments
end

class Appointment < ApplicationRecord
  belongs_to :physician, inverse_of: :appointments
  belongs_to :patient, inverse_of: :appointments
end

class Patient < ApplicationRecord
  has_many :appointments
  has_many :physicians, through: :appointments
end
```

### Configurable attributes

Name | Default value | Configurable values
--- | --- | ---
Include | `app/models/**/*.rb` | Array

## Rails/LexicallyScopedActionFilter

Enabled by default | Supports autocorrection
--- | ---
Enabled | No

This cop checks that methods specified in the filter's `only`
or `except` options are explicitly defined in the class or module.

You can specify methods of superclass or methods added by mixins
on the filter, but these confuse developers. If you specify methods
where are defined on another classes or modules, you should define
the filter in that class or module.

### Examples

```ruby
# bad
class LoginController < ApplicationController
  before_action :require_login, only: %i[index settings logout]

  def index
  end
end

# good
class LoginController < ApplicationController
  before_action :require_login, only: %i[index settings logout]

  def index
  end

  def settings
  end

  def logout
  end
end
```
```ruby
# bad
module FooMixin
  extend ActiveSupport::Concern

  included do
    before_action proc { authenticate }, only: :foo
  end
end

# good
module FooMixin
  extend ActiveSupport::Concern

  included do
    before_action proc { authenticate }, only: :foo
  end

  def foo
    # something
  end
end
```

### Configurable attributes

Name | Default value | Configurable values
--- | --- | ---
Include | `app/controllers/**/*.rb` | Array

### References

* [https://github.com/rubocop-hq/rails-style-guide#lexically-scoped-action-filter](https://github.com/rubocop-hq/rails-style-guide#lexically-scoped-action-filter)

## Rails/NotNullColumn

Enabled by default | Supports autocorrection
--- | ---
Enabled | No

This cop checks for add_column call with NOT NULL constraint
in migration file.

### Examples

```ruby
# bad
add_column :users, :name, :string, null: false
add_reference :products, :category, null: false

# good
add_column :users, :name, :string, null: true
add_column :users, :name, :string, null: false, default: ''
add_reference :products, :category
add_reference :products, :category, null: false, default: 1
```

### Configurable attributes

Name | Default value | Configurable values
--- | --- | ---
Include | `db/migrate/*.rb` | Array

## Rails/Output

Enabled by default | Supports autocorrection
--- | ---
Enabled | No

This cop checks for the use of output calls like puts and print

### Examples

```ruby
# bad
puts 'A debug message'
pp 'A debug message'
print 'A debug message'

# good
Rails.logger.debug 'A debug message'
```

### Configurable attributes

Name | Default value | Configurable values
--- | --- | ---
Include | `app/**/*.rb`, `config/**/*.rb`, `db/**/*.rb`, `lib/**/*.rb` | Array

## Rails/OutputSafety

Enabled by default | Supports autocorrection
--- | ---
Enabled | No

This cop checks for the use of output safety calls like html_safe,
raw, and safe_concat. These methods do not escape content. They
simply return a SafeBuffer containing the content as is. Instead,
use safe_join to join content and escape it and concat to
concatenate content and escape it, ensuring its safety.

### Examples

```ruby
user_content = "<b>hi</b>"

# bad
"<p>#{user_content}</p>".html_safe
# => ActiveSupport::SafeBuffer "<p><b>hi</b></p>"

# good
content_tag(:p, user_content)
# => ActiveSupport::SafeBuffer "<p><b>hi</b></p>"

# bad
out = ""
out << "<li>#{user_content}</li>"
out << "<li>#{user_content}</li>"
out.html_safe
# => ActiveSupport::SafeBuffer "<li><b>hi</b></li><li><b>hi</b></li>"

# good
out = []
out << content_tag(:li, user_content)
out << content_tag(:li, user_content)
safe_join(out)
# => ActiveSupport::SafeBuffer
#    "<li><b>hi</b></li><li><b>hi</b></li>"

# bad
out = "<h1>trusted content</h1>".html_safe
out.safe_concat(user_content)
# => ActiveSupport::SafeBuffer "<h1>trusted_content</h1><b>hi</b>"

# good
out = "<h1>trusted content</h1>".html_safe
out.concat(user_content)
# => ActiveSupport::SafeBuffer
#    "<h1>trusted_content</h1><b>hi</b>"

# safe, though maybe not good style
out = "trusted content"
result = out.concat(user_content)
# => String "trusted content<b>hi</b>"
# because when rendered in ERB the String will be escaped:
# <%= result %>
# => trusted content<b>hi</b>

# bad
(user_content + " " + content_tag(:span, user_content)).html_safe
# => ActiveSupport::SafeBuffer "<b>hi</b> <span><b>hi</b></span>"

# good
safe_join([user_content, " ", content_tag(:span, user_content)])
# => ActiveSupport::SafeBuffer
#    "<b>hi</b> <span><b>hi</b></span>"
```

## Rails/PluralizationGrammar

Enabled by default | Supports autocorrection
--- | ---
Enabled | Yes

This cop checks for correct grammar when using ActiveSupport's
core extensions to the numeric classes.

### Examples

```ruby
# bad
3.day.ago
1.months.ago

# good
3.days.ago
1.month.ago
```

## Rails/Presence

Enabled by default | Supports autocorrection
--- | ---
Enabled | Yes

This cop checks code that can be written more easily using
`Object#presence` defined by Active Support.

### Examples

```ruby
# bad
a.present? ? a : nil

# bad
!a.present? ? nil : a

# bad
a.blank? ? nil : a

# bad
!a.blank? ? a : nil

# good
a.presence
```
```ruby
# bad
a.present? ? a : b

# bad
!a.present? ? b : a

# bad
a.blank? ? b : a

# bad
!a.blank? ? a : b

# good
a.presence || b
```

## Rails/Present

Enabled by default | Supports autocorrection
--- | ---
Enabled | Yes

This cop checks for code that can be written with simpler conditionals
using `Object#present?` defined by Active Support.

simpler conditionals.

### Examples

#### NotNilAndNotEmpty: true (default)

```ruby
# Converts usages of `!nil? && !empty?` to `present?`

# bad
!foo.nil? && !foo.empty?

# bad
foo != nil && !foo.empty?

# good
foo.present?
```
#### NotBlank: true (default)

```ruby
# Converts usages of `!blank?` to `present?`

# bad
!foo.blank?

# bad
not foo.blank?

# good
foo.present?
```
#### UnlessBlank: true (default)

```ruby
# Converts usages of `unless blank?` to `if present?`

# bad
something unless foo.blank?

# good
something if foo.present?
```

### Configurable attributes

Name | Default value | Configurable values
--- | --- | ---
NotNilAndNotEmpty | `true` | Boolean
NotBlank | `true` | Boolean
UnlessBlank | `true` | Boolean

## Rails/ReadWriteAttribute

Enabled by default | Supports autocorrection
--- | ---
Enabled | Yes

This cop checks for the use of the read_attribute or write_attribute
methods, and recommends square brackets instead.

If an attribute is missing from the instance (for example, when
initialized by a partial `select`) then read_attribute will return nil,
but square brackets will raise an ActiveModel::MissingAttributeError.

Explicitly raising an error in this situation is preferable, and that
is why rubocop recommends using square brackets.

### Examples

```ruby
# bad
x = read_attribute(:attr)
write_attribute(:attr, val)

# good
x = self[:attr]
self[:attr] = val
```

### Configurable attributes

Name | Default value | Configurable values
--- | --- | ---
Include | `app/models/**/*.rb` | Array

### References

* [https://github.com/rubocop-hq/rails-style-guide#read-attribute](https://github.com/rubocop-hq/rails-style-guide#read-attribute)

## Rails/RedundantReceiverInWithOptions

Enabled by default | Supports autocorrection
--- | ---
Enabled | Yes

This cop checks for redundant receiver in `with_options`.
Receiver is implicit from Rails 4.2 or higher.

### Examples

```ruby
# bad
class Account < ApplicationRecord
  with_options dependent: :destroy do |assoc|
    assoc.has_many :customers
    assoc.has_many :products
    assoc.has_many :invoices
    assoc.has_many :expenses
  end
end

# good
class Account < ApplicationRecord
  with_options dependent: :destroy do
    has_many :customers
    has_many :products
    has_many :invoices
    has_many :expenses
  end
end
```
```ruby
# bad
with_options options: false do |merger|
  merger.invoke(merger.something)
end

# good
with_options options: false do
  invoke(something)
end

# good
client = Client.new
with_options options: false do |merger|
  client.invoke(merger.something, something)
end

# ok
# When `with_options` includes a block, all scoping scenarios
# cannot be evaluated. Thus, it is ok to include the explicit
# receiver.
with_options options: false do |merger|
  merger.invoke
  with_another_method do |another_receiver|
    merger.invoke(another_receiver)
  end
end
```

## Rails/RefuteMethods

Enabled by default | Supports autocorrection
--- | ---
Enabled | Yes

Use `assert_not` methods instead of `refute` methods.

### Examples

```ruby
# bad
refute false
refute_empty [1, 2, 3]
refute_equal true, false

# good
assert_not false
assert_not_empty [1, 2, 3]
assert_not_equal true, false
```

### Configurable attributes

Name | Default value | Configurable values
--- | --- | ---
Include | `**/test/**/*` | Array

## Rails/RelativeDateConstant

Enabled by default | Supports autocorrection
--- | ---
Enabled | Yes

This cop checks whether constant value isn't relative date.
Because the relative date will be evaluated only once.

### Examples

```ruby
# bad
class SomeClass
  EXPIRED_AT = 1.week.since
end

# good
class SomeClass
  def self.expired_at
    1.week.since
  end
end
```

## Rails/RequestReferer

Enabled by default | Supports autocorrection
--- | ---
Enabled | Yes

This cop checks for consistent uses of `request.referer` or
`request.referrer`, depending on the cop's configuration.

### Examples

#### EnforcedStyle: referer (default)

```ruby
# bad
request.referrer

# good
request.referer
```
#### EnforcedStyle: referrer

```ruby
# bad
request.referer

# good
request.referrer
```

### Configurable attributes

Name | Default value | Configurable values
--- | --- | ---
EnforcedStyle | `referer` | `referer`, `referrer`

## Rails/ReversibleMigration

Enabled by default | Supports autocorrection
--- | ---
Enabled | No

This cop checks whether the change method of the migration file is
reversible.

### Examples

```ruby
# bad
def change
  change_table :users do |t|
    t.remove :name
  end
end

# good
def change
  create_table :users do |t|
    t.string :name
  end
end

# good
def change
  reversible do |dir|
    change_table :users do |t|
      dir.up do
        t.column :name, :string
      end

      dir.down do
        t.remove :name
      end
    end
  end
end
```
```ruby
# drop_table

# bad
def change
  drop_table :users
end

# good
def change
  drop_table :users do |t|
    t.string :name
  end
end
```
```ruby
# change_column_default

# bad
def change
  change_column_default(:suppliers, :qualification, 'new')
end

# good
def change
  change_column_default(:posts, :state, from: nil, to: "draft")
end
```
```ruby
# remove_column

# bad
def change
  remove_column(:suppliers, :qualification)
end

# good
def change
  remove_column(:suppliers, :qualification, :string)
end
```
```ruby
# remove_foreign_key

# bad
def change
  remove_foreign_key :accounts, column: :owner_id
end

# good
def change
  remove_foreign_key :accounts, :branches
end
```
```ruby
# change_table

# bad
def change
  change_table :users do |t|
    t.remove :name
    t.change_default :authorized, 1
    t.change :price, :string
  end
end

# good
def change
  change_table :users do |t|
    t.string :name
  end
end

# good
def change
  reversible do |dir|
    change_table :users do |t|
      dir.up do
        t.change :price, :string
      end

      dir.down do
        t.change :price, :integer
      end
    end
  end
end
```

### Configurable attributes

Name | Default value | Configurable values
--- | --- | ---
Include | `db/migrate/*.rb` | Array

### References

* [https://github.com/rubocop-hq/rails-style-guide#reversible-migration](https://github.com/rubocop-hq/rails-style-guide#reversible-migration)
* [http://api.rubyonrails.org/classes/ActiveRecord/Migration/CommandRecorder.html](http://api.rubyonrails.org/classes/ActiveRecord/Migration/CommandRecorder.html)

## Rails/SafeNavigation

Enabled by default | Supports autocorrection
--- | ---
Enabled | Yes

This cop converts usages of `try!` to `&.`. It can also be configured
to convert `try`. It will convert code to use safe navigation if the
target Ruby version is set to 2.3+

### Examples

```ruby
# ConvertTry: false
  # bad
  foo.try!(:bar)
  foo.try!(:bar, baz)
  foo.try!(:bar) { |e| e.baz }

  foo.try!(:[], 0)

  # good
  foo.try(:bar)
  foo.try(:bar, baz)
  foo.try(:bar) { |e| e.baz }

  foo&.bar
  foo&.bar(baz)
  foo&.bar { |e| e.baz }

# ConvertTry: true
  # bad
  foo.try!(:bar)
  foo.try!(:bar, baz)
  foo.try!(:bar) { |e| e.baz }
  foo.try(:bar)
  foo.try(:bar, baz)
  foo.try(:bar) { |e| e.baz }

  # good
  foo&.bar
  foo&.bar(baz)
  foo&.bar { |e| e.baz }
```

### Configurable attributes

Name | Default value | Configurable values
--- | --- | ---
ConvertTry | `false` | Boolean

## Rails/SaveBang

Enabled by default | Supports autocorrection
--- | ---
Disabled | Yes

This cop identifies possible cases where Active Record save! or related
should be used instead of save because the model might have failed to
save and an exception is better than unhandled failure.

This will ignore calls that return a boolean for success if the result
is assigned to a variable or used as the condition in an if/unless
statement.  It will also ignore calls that return a model assigned to a
variable that has a call to `persisted?`. Finally, it will ignore any
call with more than 2 arguments as that is likely not an Active Record
call or a Model.update(id, attributes) call.

### Examples

```ruby
# bad
user.save
user.update(name: 'Joe')
user.find_or_create_by(name: 'Joe')
user.destroy

# good
unless user.save
  # ...
end
user.save!
user.update!(name: 'Joe')
user.find_or_create_by!(name: 'Joe')
user.destroy!

user = User.find_or_create_by(name: 'Joe')
unless user.persisted?
  # ...
end
```

### References

* [https://github.com/rubocop-hq/rails-style-guide#save-bang](https://github.com/rubocop-hq/rails-style-guide#save-bang)

## Rails/ScopeArgs

Enabled by default | Supports autocorrection
--- | ---
Enabled | No

This cop checks for scope calls where it was passed
a method (usually a scope) instead of a lambda/proc.

### Examples

```ruby
# bad
scope :something, where(something: true)

# good
scope :something, -> { where(something: true) }
```

### Configurable attributes

Name | Default value | Configurable values
--- | --- | ---
Include | `app/models/**/*.rb` | Array

## Rails/SkipsModelValidations

Enabled by default | Supports autocorrection
--- | ---
Enabled | No

This cop checks for the use of methods which skip
validations which are listed in
http://guides.rubyonrails.org/active_record_validations.html#skipping-validations

### Examples

```ruby
# bad
Article.first.decrement!(:view_count)
DiscussionBoard.decrement_counter(:post_count, 5)
Article.first.increment!(:view_count)
DiscussionBoard.increment_counter(:post_count, 5)
person.toggle :active
product.touch
Billing.update_all("category = 'authorized', author = 'David'")
user.update_attribute(:website, 'example.com')
user.update_columns(last_request_at: Time.current)
Post.update_counters 5, comment_count: -1, action_count: 1

# good
user.update(website: 'example.com')
FileUtils.touch('file')
```

### Configurable attributes

Name | Default value | Configurable values
--- | --- | ---
Blacklist | `decrement!`, `decrement_counter`, `increment!`, `increment_counter`, `toggle!`, `touch`, `update_all`, `update_attribute`, `update_column`, `update_columns`, `update_counters` | Array

### References

* [http://guides.rubyonrails.org/active_record_validations.html#skipping-validations](http://guides.rubyonrails.org/active_record_validations.html#skipping-validations)

## Rails/TimeZone

Enabled by default | Supports autocorrection
--- | ---
Enabled | No

This cop checks for the use of Time methods without zone.

Built on top of Ruby on Rails style guide (https://github.com/rubocop-hq/rails-style-guide#time)
and the article http://danilenko.org/2012/7/6/rails_timezones/ .

Two styles are supported for this cop. When EnforcedStyle is 'strict'
then only use of Time.zone is allowed.

When EnforcedStyle is 'flexible' then it's also allowed
to use Time.in_time_zone.

### Examples

#### EnforcedStyle: strict

```ruby
# `strict` means that `Time` should be used with `zone`.

# bad
Time.now
Time.parse('2015-03-02 19:05:37')

# bad
Time.current
Time.at(timestamp).in_time_zone

# good
Time.zone.now
Time.zone.parse('2015-03-02 19:05:37')
```
#### EnforcedStyle: flexible (default)

```ruby
# `flexible` allows usage of `in_time_zone` instead of `zone`.

# bad
Time.now
Time.parse('2015-03-02 19:05:37')

# good
Time.zone.now
Time.zone.parse('2015-03-02 19:05:37')

# good
Time.current
Time.at(timestamp).in_time_zone
```

### Configurable attributes

Name | Default value | Configurable values
--- | --- | ---
EnforcedStyle | `flexible` | `strict`, `flexible`

### References

* [https://github.com/rubocop-hq/rails-style-guide#time](https://github.com/rubocop-hq/rails-style-guide#time)
* [http://danilenko.org/2012/7/6/rails_timezones](http://danilenko.org/2012/7/6/rails_timezones)

## Rails/UniqBeforePluck

Enabled by default | Supports autocorrection
--- | ---
Enabled | Yes

Prefer the use of uniq (or distinct), before pluck instead of after.

The use of uniq before pluck is preferred because it executes within
the database.

This cop has two different enforcement modes. When the EnforcedStyle
is conservative (the default) then only calls to pluck on a constant
(i.e. a model class) before uniq are added as offenses.

When the EnforcedStyle is aggressive then all calls to pluck before
uniq are added as offenses. This may lead to false positives as the cop
cannot distinguish between calls to pluck on an ActiveRecord::Relation
vs a call to pluck on an ActiveRecord::Associations::CollectionProxy.

Autocorrect is disabled by default for this cop since it may generate
false positives.

### Examples

#### EnforcedStyle: conservative (default)

```ruby
# bad
Model.pluck(:id).uniq

# good
Model.uniq.pluck(:id)
```
#### EnforcedStyle: aggressive

```ruby
# bad
# this will return a Relation that pluck is called on
Model.where(cond: true).pluck(:id).uniq

# bad
# an association on an instance will return a CollectionProxy
instance.assoc.pluck(:id).uniq

# bad
Model.pluck(:id).uniq

# good
Model.uniq.pluck(:id)
```

### Configurable attributes

Name | Default value | Configurable values
--- | --- | ---
EnforcedStyle | `conservative` | `conservative`, `aggressive`
AutoCorrect | `false` | Boolean

## Rails/UnknownEnv

Enabled by default | Supports autocorrection
--- | ---
Enabled | No

This cop checks that environments called with `Rails.env` predicates
exist.

### Examples

```ruby
# bad
Rails.env.proudction?

# good
Rails.env.production?
```

### Configurable attributes

Name | Default value | Configurable values
--- | --- | ---
Environments | `development`, `test`, `production` | Array

## Rails/Validation

Enabled by default | Supports autocorrection
--- | ---
Enabled | Yes

This cop checks for the use of old-style attribute validation macros.

### Examples

```ruby
# bad
validates_acceptance_of :foo
validates_confirmation_of :foo
validates_exclusion_of :foo
validates_format_of :foo
validates_inclusion_of :foo
validates_length_of :foo
validates_numericality_of :foo
validates_presence_of :foo
validates_size_of :foo
validates_uniqueness_of :foo

# good
validates :foo, acceptance: true
validates :foo, confirmation: true
validates :foo, exclusion: true
validates :foo, format: true
validates :foo, inclusion: true
validates :foo, length: true
validates :foo, numericality: true
validates :foo, presence: true
validates :foo, size: true
validates :foo, uniqueness: true
```

### Configurable attributes

Name | Default value | Configurable values
--- | --- | ---
Include | `app/models/**/*.rb` | Array


text:
using System;
using Cirrious.CrossCore;
using Cirrious.CrossCore.Platform;
using Cirrious.CrossCore.Plugins;
using Cirrious.MvvmCross.Touch.Platform;
using Cirrious.MvvmCross.Touch.Views.Presenters;
using Cirrious.MvvmCross.ViewModels;
using Cirrious.MvvmCross.Views;
using MobiliTips.MvxPlugins.MvxAms.Touch;
using MobiliTips.MvxPlugins.MvxForms;
using MvxAms.Sample.Configurations;
using MvxAms.Sample.iOS.Presenters;
using SQLitePCL;
using UIKit;
using Xamarin.Forms;

namespace MvxAms.Sample.iOS
{
	public class Setup : MvxTouchSetup
	{
		public Setup(MvxApplicationDelegate applicationDelegate, UIWindow window)
            : base(applicationDelegate, window)
		{
		}

		protected override IMvxApplication CreateApp()
		{
			return new App();
		}

        protected override IMvxTrace CreateDebugTrace()
        {
            return new DebugTrace();
        }

	    protected override void InitializeLastChance()
	    {
	        base.InitializeLastChance();

            Mvx.RegisterSingleton<IMvxAmsTouchTopViewController>(new MvxAmsTouchTopViewController(Window.RootViewController));

            SQLitePCL.CurrentPlatform.Init();
	    }

	    protected override IMvxTouchViewPresenter CreatePresenter()
        {
            Forms.Init();

            var presenter = new MvxFormsTouchViewPresenter(new MvxFormsApp(), Window);
            Mvx.RegisterSingleton<IMvxViewPresenter>(presenter);

            return presenter;
        }

        protected override IMvxPluginConfiguration GetPluginConfiguration(Type plugin)
        {
            if (plugin == typeof (MobiliTips.MvxPlugins.MvxAms.Touch.Plugin))
                return new MvxAmsPluginConfiguration();

            if (plugin == typeof(MobiliTips.MvxPlugins.MvxAms.LocalStore.PluginLoader))
                return new MvxAmsPluginLocalStoreExtensionConfiguration(Environment.GetFolderPath(Environment.SpecialFolder.Personal));

            return base.GetPluginConfiguration(plugin);
        }
	}
}


text:
<?php

namespace Bitporch\Forum;

use Bitporch\Forum\Console\InstallCommand;
use Bitporch\Forum\Models\Discussion;
use Bitporch\Forum\Models\Group;
use Bitporch\Forum\Models\Post;
use Bitporch\Forum\Observers\DiscussionObserver;
use Bitporch\Forum\Observers\PostObserver;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;

class ForumServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        if ($this->app->runningInConsole()) {
            $this->commands([
                InstallCommand::class,
            ]);
        }

        $this->loadTranslationsFrom(__DIR__.'/../resources/translations', 'forum');

        $this->publishes([
            __DIR__.'/../config/forum.php' => config_path('forum.php'),
        ], 'config');

        $this->publishes([
            __DIR__.'/../resources/lang' => resource_path('lang/vendor/forum'),
        ], 'forum');

        $this->registerRouteBindings();
        $this->registerPackageNamespaces();
        $this->registerModelObservers();
        $this->registerBladeDirectives();

        View::composer('*', 'Bitporch\Forum\ViewComposers\GroupComposer');
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Register route bindings for models. We don't need to do this since we're following
     * the conventions by which route model bindings will happen automatically,
     * but this makes it obvious that the package relies on it.
     *
     * @return void
     */
    public function registerRouteBindings()
    {
        Route::model('discussion', Discussion::class);
        Route::model('group', Group::class);
        Route::model('post', Post::class);
    }

    /**
     * Define the application migrations, routes and views.
     *
     * @return void
     */
    public function registerPackageNamespaces()
    {
        $this->loadMigrationsFrom(__DIR__.'/../database/migrations');

        if (config('forum.api.enabled')) {
            $this->loadRoutesFrom(__DIR__.'/../routes/api.php');
        }

        if (config('forum.web.enabled')) {
            $this->loadRoutesFrom(__DIR__.'/../routes/web.php');
        }

        $this->loadViewsFrom(__DIR__.'/../resources/views', 'forum');
    }

    /**
     * Register the model observers.
     *
     * @return void
     */
    public function registerModelObservers()
    {
        Discussion::observe(DiscussionObserver::class);
        Post::observe(PostObserver::class);
    }

    /**
     * @return void
     */
    public function registerBladeDirectives()
    {
        Blade::directive('error', function ($type) {
            return '<?php
                if($errors->has('.$type.')) {
                    echo "
                        {$errors->first('.$type.')}
                    ";
                }
                ?>
            ';
        });
    }
}


text:
Last Modified 2017.8.30

Jetty Maven Plugin

With the Jetty Maven Plugin, you can test web apps without installing a server.

Create a webapp archetype.

C:\ Command Prompt

mvn archetype:generate -Dfilter=maven-archetype-webapp

C:\ Command Prompt

Define value for property 'groupId': : net.java_school.test
Define value for property 'artifactId': : hello
Define value for property 'version':  1.0-SNAPSHOT: :
Define value for property 'package':  net.java_school.hello: :

Import the Maven project into Eclipse by selecting Import - Import - Existing Maven Project.

Modify web.xml as follows.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  version="3.1"
  metadata-complete="true">

</web-app>

Modify pom.xml as follows.

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>net.java_school.test</groupId>
	<artifactId>examples</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>hello</name>
	<url>http://maven.apache.org</url>

	<properties>
		<jdk.version>1.8</jdk.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<!-- Servlet JSP JSTL -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>javax.servlet.jsp-api</artifactId>
			<version>2.3.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>jstl</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
	</dependencies>

	<build>
		<finalName>hello</finalName>
		<pluginManagement>
			<plugins>
				<plugin>
					<groupId>org.apache.maven.plugins</groupId>
					<artifactId>maven-compiler-plugin</artifactId>
					<version>3.6.2</version>
					<configuration>
						<source>${jdk.version}</source>
						<target>${jdk.version}</target>
						<encoding>UTF-8</encoding>
					</configuration>
				</plugin>
				<plugin>
					<groupId>org.eclipse.jetty</groupId>
					<artifactId>jetty-maven-plugin</artifactId>
					<version>9.4.10.v20180503</version>
				</plugin>
			</plugins>
		</pluginManagement>
	</build>

</project>

Select the latest jetty-maven-plugin distribution from https://mvnrepository.com/artifact/org.eclipse.jetty/jetty-maven-plugin and add it to the plug-in instead of the dependency. (See the highlighted section above)

Run jetty server as shown below.

C:\ Command Prompt

mvn jetty:run

Visit http://localhost:8080.

References

http://www.eclipse.org/jetty/documentation/9.3.x/jetty-maven-plugin.html

https://mvnrepository.com/artifact/org.eclipse.jetty/jetty-maven-plugin

https://mvnrepository.com/artifact/org.eclipse.jetty/jetty-maven-plugin/9.4.6.v20170531

https://maven.apache.org/plugins/maven-compiler-plugin/usage.html

https://maven.apache.org/plugins/maven-compiler-plugin/examples/set-compiler-source-and-target.html

Related Articles

Jetty Maven Plugin

Basic bulletin board

Hierarchical bulletin board

Hierarchical bulletin board using Oracle Hierarchical query

Model 1 bulletin board

Model 2 bulletin board

Model 2 bulletin board for Oracle using DBCP

Model 2 bulletin board for MySQL using DBCP

REST example


text:
package com.example.simplecropviewsample;

import android.app.Application;
import android.graphics.Bitmap;

public class AppController extends Application{
    private static final String TAG = AppController.class.getSimpleName();
    public Bitmap cropped = null;

    @Override
    public void onCreate(){
        super.onCreate();
        // load custom font
        FontUtils.loadFont(getApplicationContext(), "Roboto-Light.ttf");
    }
}


text:
package org.apache.kafka.streams.kstream;

import org.apache.kafka.common.annotation.InterfaceStability;

/**
 * A {@code TransformerSupplier} interface which can create one or more {@link Transformer} instances.
 *
 * @param <K> key type
 * @param <V> value type
 * @param <R> {@link org.apache.kafka.streams.KeyValue KeyValue} return type (both key and value type can be set
 *            arbitrarily)
 * @see Transformer
 * @see KStream#transform(TransformerSupplier, String...)
 * @see ValueTransformer
 * @see ValueTransformerSupplier
 * @see KStream#transformValues(ValueTransformerSupplier, String...)
 */
@InterfaceStability.Unstable
public interface TransformerSupplier<K, V, R> {

    /**
     * Return a new {@link Transformer} instance.
     *
     * @return a new {@link Transformer} instance
     */
    Transformer<K, V, R> get();
}


text:
import os
from setuptools import find_packages, setup

# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))

setup(
    name='django-json-feed',
    version='1.0',
    packages=find_packages(),
    include_package_data=True,
    license='BSD License',
    description='Implement JSON feeds in Django using the syndication framework.',
    long_description='Implement JSON feeds in Django using the syndication framework that conform to the JSON Feed standard.',
    url='https://github.com/chris-erickson/django-json-feed',
    author='Chris Erickson',
    author_email='chris+django-json-feed@groundedwing.com',
    classifiers=[
        'Environment :: Web Environment',
        'Framework :: Django',
        'Framework :: Django :: 1.11',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
    ],
)


text:
import os

if os.environ.get('LIBRATO_INSTRUMENT_PYTHON'):
    from .bootstrap import init
    init()


text:
"""
    SALTS XBMC Addon
    Copyright (C) 2014 tknorris

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU 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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""
import scraper
import urllib
import urlparse
import re
import json
import xbmcaddon
import xbmc
from salts_lib import log_utils
from salts_lib import dom_parser
from salts_lib.constants import VIDEO_TYPES
from salts_lib.constants import QUALITIES
from salts_lib.constants import Q_ORDER

BASE_URL = 'https://mvsnap.com'

class Mvsnap_Scraper(scraper.Scraper):
    base_url = BASE_URL

    def __init__(self, timeout=scraper.DEFAULT_TIMEOUT):
        self.timeout = timeout
        self.base_url = xbmcaddon.Addon().getSetting('%s-base_url' % (self.get_name()))

    @classmethod
    def provides(cls):
        return frozenset([VIDEO_TYPES.MOVIE])

    @classmethod
    def get_name(cls):
        return 'mvsnap'

    def resolve_link(self, link):
        return link

    def format_source_label(self, item):
        return '[%s] %s' % (item['quality'], item['host'])

    def get_sources(self, video):
        source_url = self.get_url(video)
        hosters = []
        if source_url:
            url = urlparse.urljoin(self.base_url, source_url)
            html = self._http_get(url, cache_limit=.5)
            fragment = dom_parser.parse_dom(html, 'select', {'id': 'myDropdown'})
            if fragment:
                fragment = fragment[0]
                for match in re.finditer('<option\s+value="([^"]+)', fragment):
                    stream_url = match.group(1)
                    stream_url = urlparse.urljoin(self.base_url, stream_url)
                    stream_url = self._http_get(stream_url, allow_redirect=False, cache_limit=.5)
                    hoster = {'multi-part': False, 'host': self._get_direct_hostname(stream_url), 'class': self, 'quality': self._gv_get_quality(stream_url), 'views': None, 'rating': None, 'url': stream_url, 'direct': True}
                    hosters.append(hoster)
        return hosters

    def get_url(self, video):
        return super(Mvsnap_Scraper, self)._default_get_url(video)

    def search(self, video_type, title, year):
        search_url = urlparse.urljoin(self.base_url, '/v1/api/search?query=')
        search_url += urllib.quote_plus(title)
        html = self._http_get(search_url, cache_limit=.25)
        results = []
        if html:
            try:
                js_data = json.loads(html)
            except ValueError:
                log_utils.log('Invalid JSON returned: %s: %s' % (search_url, html), xbmc.LOGWARNING)
            else:
                if 'movies' in js_data:
                    for item in js_data['movies']:
                        if item['type'] != 'movies':
                            continue

                        match = re.search('(.*)(?:\s+\((\d{4})\))', item['title'])
                        if match:
                            match_title, match_year = match.groups()
                        else:
                            match_title = item['title']
                            match_year = ''

                        result = {'title': match_title, 'url': '/movies/%s' % (item['slug']), 'year': match_year}
                        results.append(result)
        return results

    def _http_get(self, url, data=None, allow_redirect=True, cache_limit=8):
        return super(Mvsnap_Scraper, self)._cached_http_get(url, self.base_url, self.timeout, data=data, allow_redirect=allow_redirect, cache_limit=cache_limit)


text:
from astropy.io import fits
import desispec.tpcorrparam

def read_tpcorrparam(fn):
    mean = fits.getdata(fn, 'MEAN')
    spatial = fits.getdata(fn, 'SPATIAL')
    pca = fits.getdata(fn, 'PCA')
    return desispec.tpcorrparam.TPCorrParam(mean, spatial, pca)


text:
#pragma once
#include <aws/lightsail/Lightsail_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace Lightsail
{
namespace Model
{

  /**
   *
Lightsail throws this exception when user input does not conform to the
   * validation rules of an input field.

Domain and distribution APIs
   * are only available in the N. Virginia (us-east-1) AWS Region.
   * Please set your AWS Region configuration to us-east-1 to create,
   * view, or edit these resources.

See Also:
   AWS
   * API Reference

   */
  class AWS_LIGHTSAIL_API InvalidInputException
  {
  public:
    InvalidInputException();
    InvalidInputException(Aws::Utils::Json::JsonView jsonValue);
    InvalidInputException& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    inline const Aws::String& GetCode() const{ return m_code; }

    inline bool CodeHasBeenSet() const { return m_codeHasBeenSet; }

    inline void SetCode(const Aws::String& value) { m_codeHasBeenSet = true; m_code = value; }

    inline void SetCode(Aws::String&& value) { m_codeHasBeenSet = true; m_code = std::move(value); }

    inline void SetCode(const char* value) { m_codeHasBeenSet = true; m_code.assign(value); }

    inline InvalidInputException& WithCode(const Aws::String& value) { SetCode(value); return *this;}

    inline InvalidInputException& WithCode(Aws::String&& value) { SetCode(std::move(value)); return *this;}

    inline InvalidInputException& WithCode(const char* value) { SetCode(value); return *this;}

    inline const Aws::String& GetDocs() const{ return m_docs; }

    inline bool DocsHasBeenSet() const { return m_docsHasBeenSet; }

    inline void SetDocs(const Aws::String& value) { m_docsHasBeenSet = true; m_docs = value; }

    inline void SetDocs(Aws::String&& value) { m_docsHasBeenSet = true; m_docs = std::move(value); }

    inline void SetDocs(const char* value) { m_docsHasBeenSet = true; m_docs.assign(value); }

    inline InvalidInputException& WithDocs(const Aws::String& value) { SetDocs(value); return *this;}

    inline InvalidInputException& WithDocs(Aws::String&& value) { SetDocs(std::move(value)); return *this;}

    inline InvalidInputException& WithDocs(const char* value) { SetDocs(value); return *this;}

    inline const Aws::String& GetMessage() const{ return m_message; }

    inline bool MessageHasBeenSet() const { return m_messageHasBeenSet; }

    inline void SetMessage(const Aws::String& value) { m_messageHasBeenSet = true; m_message = value; }

    inline void SetMessage(Aws::String&& value) { m_messageHasBeenSet = true; m_message = std::move(value); }

    inline void SetMessage(const char* value) { m_messageHasBeenSet = true; m_message.assign(value); }

    inline InvalidInputException& WithMessage(const Aws::String& value) { SetMessage(value); return *this;}

    inline InvalidInputException& WithMessage(Aws::String&& value) { SetMessage(std::move(value)); return *this;}

    inline InvalidInputException& WithMessage(const char* value) { SetMessage(value); return *this;}

    inline const Aws::String& GetTip() const{ return m_tip; }

    inline bool TipHasBeenSet() const { return m_tipHasBeenSet; }

    inline void SetTip(const Aws::String& value) { m_tipHasBeenSet = true; m_tip = value; }

    inline void SetTip(Aws::String&& value) { m_tipHasBeenSet = true; m_tip = std::move(value); }

    inline void SetTip(const char* value) { m_tipHasBeenSet = true; m_tip.assign(value); }

    inline InvalidInputException& WithTip(const Aws::String& value) { SetTip(value); return *this;}

    inline InvalidInputException& WithTip(Aws::String&& value) { SetTip(std::move(value)); return *this;}

    inline InvalidInputException& WithTip(const char* value) { SetTip(value); return *this;}

  private:

    Aws::String m_code;
    bool m_codeHasBeenSet;

    Aws::String m_docs;
    bool m_docsHasBeenSet;

    Aws::String m_message;
    bool m_messageHasBeenSet;

    Aws::String m_tip;
    bool m_tipHasBeenSet;
  };

} // namespace Model
} // namespace Lightsail
} // namespace Aws


text:
package gov.sandia.cognition.statistics;

import gov.sandia.cognition.math.Permutation;
import gov.sandia.cognition.math.matrix.Vector;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Random;

/**
 * A utility class for sampling.
 *
 * @author  Justin Basilico
 * @since   3.1
 */
public class DiscreteSamplingUtil
{

    /**
     * Samples an random index according to the given array of probabilities.
     *
     * @param   random
     *      The random number generator to use.
     * @param   probabilities
     *      The array of probabilities. Must sum to 1.0.
     * @return
     *      A random index sampled according to the given probabilities.
     */
    public static int sampleIndexFromProbabilities(
        final Random random,
        final double[] probabilities)
    {
        // Randomly pick a number between 0.0 and 1.0.
        double value = random.nextDouble();

        final int lastIndex = probabilities.length - 1;
        for (int i = 0; i < lastIndex; i++)
        {
            value -= probabilities[i];
            if (value <= 0.0)
            {
                // This index was selected.
                return i;
            }
        }

        return lastIndex;
    }

    /**
     * Samples an random index according to the given vector of probabilities.
     *
     * @param   random
     *      The random number generator to use.
     * @param   probabilities
     *      The vector of probabilities. Must sum to 1.0.
     * @return
     *      A random index sampled according to the given probabilities.
     */
    public static int sampleIndexFromProbabilities(
        final Random random,
        final Vector probabilities)
    {
        // Randomly pick a number between 0.0 and 1.0.
        double value = random.nextDouble();

        final int lastIndex = probabilities.getDimensionality() - 1;
        for (int i = 0; i < lastIndex; i++)
        {
            value -= probabilities.getElement(i);
            if (value <= 0.0)
            {
                // This index was selected.
                return i;
            }
        }

        return lastIndex;
    }

    /**
     * Samples a random index according to the given proportions. Note that
     * calling this requires calculating the sum of the proportions first, so
     * if it is known in advance, it is more efficient to call the version of
     * this method that takes the sum of the proportions as a parameter.
     *
     * @param   random
     *      The random number generator to use.
     * @param   proportions
     *      The array of proportions. All entries must be greater than or
     *      equal to zero.
     * @return
     *      A random index sampled according to the given proportions.
     */
    public static int sampleIndexFromProportions(
        final Random random,
        final double[] proportions)
    {
        // To sample from the proportions we will need the sum.
        double proportionSum = 0.0;
        for (double value : proportions)
        {
            proportionSum += value;
        }

        return sampleIndexFromProportions(random, proportions, proportionSum);
    }

    /**
     * Samples an array of indices from a given set of proportions.
     *
     * @param   random
     *      The random number generator to use.
     * @param   proportions
     *      The array of proportions. All entries must be greater than or
     *      equal to zero.
     * @param sampleSize
     *      The number of samples to make.
     * @return
     *      A an array of random indices sampled according to the given
     *      proportions.
     */
    public static int[] sampleIndicesFromProportions(
        final Random random,
        final double[] proportions,
        final int sampleSize)
    {
        // To sample from the proportions we will need the sum.
        final int length = proportions.length;
        double proportionSum = 0.0;
        if (sampleSize == 1)
        {
            // In the case of a single sample just do one sample using the
            // sum.
            for (double value : proportions)
            {
                proportionSum += value;

            }

            // Sample one index.
            final int randomIndex = sampleIndexFromProportions(
                random, proportions, proportionSum);
            return new int[] { randomIndex };
        }
        else
        {
            // With multiple samples, create the array of cumulative proportions
            // to sample quickly from it.
            final double[] cumulativeProportions = new double[length];

            for (int i = 0; i < length; i++)
            {
                proportionSum += proportions[i];
                cumulativeProportions[i] = proportionSum;
            }

            return sampleIndicesFromCumulativeProportions(
                random, cumulativeProportions, sampleSize);
        }
    }

    /**
     * Samples a random index according to the given proportions. Note that
     * sampling according cumulative proportions may be slightly faster than
     * this method.
     *
     * @param   random
     *      The random number generator to use.
     * @param   proportions
     *      An array of proportions. None of the entries can be negative. It
     *      must sum to proportionSum.
     * @param   proportionSum
     *      The sum of the given proportions array.
     * @return
     *      An index sampled at random from the given proportions array,
     *      according to those proportions.
     */
    public static int sampleIndexFromProportions(
        final Random random,
        final double[] proportions,
        final double proportionSum)
    {
        // Generate a random number between 0.0 and the proportion sum.
        double value = random.nextDouble() * proportionSum;
        final int lastIndex = proportions.length - 1;
        for (int i = 0; i < lastIndex; i++)
        {
            value -= proportions[i];
            if (value <= 0.0)
            {
                return i;
            }
        }

        return lastIndex;
    }

    /**
     * Samples a random index from an array of cumulative proportions.
     *
     * @param   random
     *      The random number generator to use.
     * @param   cumulativeProportions
     *      The array of cumulative proportions. The entries must be
     *      non-negative and monotonically increasing.
     * @return
     *      An index of the given array samples at random according to the
     *      given cumulative proportions.
     */
    public static int sampleIndexFromCumulativeProportions(
        final Random random,
        final double[] cumulativeProportions)
    {
        // The sum of the proportions is the last value in the array.
        final int lastIndex = cumulativeProportions.length - 1;
        final double sum = cumulativeProportions[lastIndex];

        // Sample a value between 0.0 and the sum of the proportions.
        final double value = random.nextDouble() * sum;

        // Do a binary search to find the index for the value.
        int index = Arrays.binarySearch(cumulativeProportions, value);
        if (index < 0)
        {
            int insertionPoint = -index - 1;
            index = insertionPoint;
        }

        return index;
    }
    /**
     * Samples a multiple indices with replacement from an array of cumulative
     * proportions.
     *
     * @param   random
     *      The random number generator to use.
     * @param   cumulativeProportions
     *      The array of cumulative proportions. The entries must be
     *      non-negative and monotonically increasing.
     * @param   sampleSize
     *      The number of samples to draw from the cumulative proportions.
     * @return
     *      An array of indices of sampled with replacement according to
     *      the given cumulative proportions.
     */
    public static int[] sampleIndicesFromCumulativeProportions(
        final Random random,
        final double[] cumulativeProportions,
        final int sampleSize)
    {
        final int[] result = new int[sampleSize];
        for (int i = 0; i < sampleSize; i++)
        {
            result[i] = sampleIndexFromCumulativeProportions(
                random, cumulativeProportions);
        }
        return result;
    }

    /**
     * Samples a a given number of items from a list with replacement.
     *
     * @param   <DataType>
     *      The type of data in the list.
     * @param   random
     *      The random number generator.
     * @param   data
     *      The list to sample from.
     * @param   sampleSize
     *      The sample size. Must be positive.
     * @return
     *      An array list of the given size sampled with replacement from the
     *      given data.
     */
    public static <DataType> ArrayList<DataType> sampleWithReplacement(
        final Random random,
        final List<? extends DataType> data,
        final int sampleSize)
    {
        final ArrayList<DataType> result = new ArrayList<DataType>(sampleSize);
        sampleWithReplacementInto(random, data, sampleSize, result);
        return result;
    }

    /**
     * Samples a a given number of items from a list with replacement and puts
     * the samples into the given collection.
     *
     * @param   <DataType>
     *      The type of data in the list.
     * @param   random
     *      The random number generator.
     * @param   data
     *      The list to sample from.
     * @param   sampleSize
     *      The sample size. Must be positive.
     * @param   result
     *      The resulting collection to sample into. All sampled elements will
     *      be added to this collection..
     */
    public static <DataType> void sampleWithReplacementInto(
        final Random random,
        final List<? extends DataType> data,
        final int sampleSize,
        final Collection<? super DataType> result)
    {
        final int dataSize = data.size();
        for (int i = 0; i < sampleSize; i++)
        {
            final int randomIndex = random.nextInt(dataSize);
            result.add(data.get(randomIndex));
        }
    }

    /**
     * Samples a a given number of items from a list without replacement.
     *
     * @param   <DataType>
     *      The type of data in the list.
     * @param   random
     *      The random number generator.
     * @param   data
     *      The list to sample from.
     * @param   sampleSize
     *      The sample size. Must be positive and less than or equal to
     *      the data size.
     * @return
     *      A list sampled without replacement from the given data. It will
     *      be of size sampleSize.
     */
    public static <DataType> List<DataType> sampleWithoutReplacement(
        final Random random,
        final List<DataType> data,
        final int sampleSize)
    {
        final int dataSize = data.size();
        if (sampleSize <= 0)
        {
            throw new IllegalArgumentException("sampleSized must be positive");
        }
        else if (sampleSize == 1)
        {
            // Only a single sample was requested.
            final int randomIndex = random.nextInt(dataSize);
            return Collections.singletonList(data.get(randomIndex));
        }
        else if (sampleSize < dataSize)
        {
            // Create a sample using a permutation.
            return Permutation.createReordering(data, random)
                .subList(0, sampleSize);
        }
        else if (sampleSize == dataSize)
        {
            // More samples than data were requested, so just return
            // the entire list.
            return Collections.unmodifiableList(data);
        }
        else
        {
            throw new IllegalArgumentException(
                "sampleSize (" + sampleSize + ") cannot be larger than "
                + "data size (" + dataSize + ")");
        }
    }
}