text:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using DevExpress.Diagram.Core;
using DevExpress.Diagram.Core.Native;
using DevExpress.Diagram.Core.Themes;
using DevExpress.XtraDiagram;
using DevExpress.XtraDiagram.Designer;
using DevExpress.XtraDiagram.Native;
using DevExpress.XtraDiagram.Utils;
using WitsWay.Utilities.Extends;
using WitsWay.Utilities.Win;

namespace WitsWay.TempTests.DiagramTest
{
    public partial class FlowDesignXtraForm : DevExpress.XtraBars.Ribbon.RibbonForm
    {
        public FlowDesignXtraForm()
        {
            InitializeComponent();
        }

        private void XtraForm1_Load(object sender, EventArgs e)
        {
            diagramControl.SelectionChanged += DiagramControl_SelectionChanged;
            diagramControl.BackgroundImageChanged += DiagramControl_BackgroundImageChanged;
            diagramControl.CustomDrawBackground += DiagramControl_CustomDrawBackground;

            //PageSize
            diagramControl.OptionsView.PageSize = new SizeF(550, 400);
            diagramControl.FitToPage();
            //GridSize
            diagramControl.OptionsView.GridSize = new SizeF(50, 50);
            //Draw Grid and Rulers
            diagramControl.OptionsView.ShowGrid = false;
            diagramControl.OptionsView.ShowRulers = false;
            //////Select Items
            ////diagramControl.SelectItems(diagramControl.Items[0], diagramControl.Items[1]);
            diagramControl.MouseClick += DiagramControl_MouseClick;
        }

        private void DiagramControl_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                //var item= diagramControl.CalcHitItem(diagramControl.PointToControl(new PointFloat(MousePosition)));
                var item = diagramControl.CalcHitItem(e.Location);
                if (item == null) return;
                if (item.IsType<DiagramConnector>())
                {
                    var connector = (DiagramConnector)item;
                    _popupMenuConnector.ShowPopup(MousePosition);
                }
                else if (item.IsType<DiagramShape>())
                {
                    var shape = (DiagramShape)item;
                    _popupMenuItem.ShowPopup(MousePosition);
                }
            }
        }

        //diagramControl.MouseHover += DiagramControl_MouseHover;
        //diagramControl.MouseMove += DiagramControl_MouseMove;
        //private void DiagramControl_MouseMove(object sender, MouseEventArgs e)
        //{
        //    var item = diagramControl.CalcHitItem(diagramControl.PointToControl(new PointFloat(MousePosition)));
        //    if (item == null) return;
        //    var shape = item as DiagramShape;
        //    UtilityHelper.ShowInfoMessage(shape.Shape.Name);
        //}

        //private void DiagramControl_MouseHover(object sender, EventArgs e)
        //{
        //    var item = diagramControl.CalcHitItem(MousePosition);//diagramControl.PointToControl(new PointFloat(MousePosition)));
        //    if (item != null)
        //    {

        //    }
        //}

        #region [Selection]

        private bool _isSelectionLocked;
        const int DefaultStrokeThickness = 2;
        const int SelectedStrokeThickness = 4;
        //void TreeListControlFocusedNodeChanged(object sender, FocusedNodeChangedEventArgs e)
        //{
        //    //DoLockedSelectionAction(() => {
        //    //    Employee selectedEmployee = treeListControl1.GetDataRecordByNode(e.Node) as Employee;
        //    //    DiagramItem diagramItem = null;
        //    //    if (selectedEmployee != null)
        //    //        diagramItem = diagramControl.Items.FirstOrDefault(x => x.DataContext == selectedEmployee);
        //    //    if (diagramItem != null)
        //    //    {
        //    //        diagramControl.SelectItem(diagramItem);
        //    //        diagramControl.BringItemsIntoView(new[] { diagramItem });
        //    //    }
        //    //    else
        //    //    {
        //    //        diagramControl.ClearSelection();
        //    //    }
        //    //});
        //}
        private void DiagramControl_SelectionChanged(object sender, DiagramSelectionChangedEventArgs e)
        {

            DoLockedSelectionAction(() =>
            {
                foreach (var diagramConnector in diagramControl.Items.OfType<DiagramConnector>())
                {
                    var isSelectionRelatedConnector = diagramControl.SelectedItems.Contains((DiagramItem)diagramConnector.BeginItem) || diagramControl.SelectedItems.Contains((DiagramItem)diagramConnector.EndItem);
                    diagramConnector.Appearance.BorderSize = isSelectionRelatedConnector ? SelectedStrokeThickness : DefaultStrokeThickness;
                }
                if (diagramControl.PrimarySelection == null) return;
                var connector = diagramControl.PrimarySelection as DiagramConnector;
                if (connector != null)
                {
                    var selectConnector = connector;
                    _propertyGrid.SelectedObject = selectConnector;
                    if (selectConnector.Tag == null) selectConnector.Tag = DateTime.Now;
                    //UtilityHelper.ShowInfoMessage(selectConnector.Tag.ToString());
                    //selectPersonLabel.Visibility = LayoutVisibility.Always;
                    //personInfoGroup.Visibility = LayoutVisibility.Never;
                }
                else
                {

                    var selectItem = diagramControl.PrimarySelection;
                    _propertyGrid.SelectedObject = selectItem;
                }

                //else
                //{
                //    selectPersonLabel.Visibility = LayoutVisibility.Never;
                //    personInfoGroup.Visibility = LayoutVisibility.Always;

                //    var container = diagramControl.PrimarySelection as DiagramContainer;
                //    var employee = diagramControl.PrimarySelection.DataContext as Employee;
                //    if (container != null && employee != null)
                //    {
                //        pictureEdit.EditValue = employee.ImageData;
                //        labelName.Text = employee.FullName;
                //        labelPhoneNumber.Text = employee.Phone;
                //        labelBirthDate.Text = employee.BirthDate.ToString("MMMM dd, yyyy");
                //        labelAddressLine.Text = employee.AddressLine1;
                //        labelFriends.Text = GetRelationsText(employee, EmployeeRelationship.Friends);
                //        labelKnowEachOther.Text = GetRelationsText(employee, EmployeeRelationship.KnowEachOther);
                //    }
                //}

                //Employee selectedEmployee = null;
                //if (diagramControl.PrimarySelection != null && diagramControl.PrimarySelection.DataContext is Employee)
                //    selectedEmployee = (Employee)diagramControl.PrimarySelection.DataContext;
                //if (selectedEmployee != null)
                //    treeListControl1.FocusedNode = treeListControl1.FindNodeByKeyID(selectedEmployee.Id);
                //else
                //    treeListControl1.FocusedNode = null;
            });
        }
        void DoLockedSelectionAction(Action action)
        {
            if (_isSelectionLocked)
                return;
            _isSelectionLocked = true;
            action();
            _isSelectionLocked = false;
        }

        #endregion

        private void _btnZoomIn_Click(object sender, EventArgs e) => diagramControl.OptionsView.ZoomFactor += 0.1f;

        private void _btnZoomOut_Click(object sender, EventArgs e) => diagramControl.OptionsView.ZoomFactor -= 0.1f;

        private void _btnClear_Click(object sender, EventArgs e) => diagramControl.Items.Clear();

        private void _btnDesign_Click(object sender, EventArgs e)
        {
            var designerForm = new DiagramDesignerForm() { ShowInTaskbar = false, WindowState = FormWindowState.Maximized };
            DiagramDesignerUtils.RunDesigner(diagramControl, designerForm);
        }

        private void _btnCopyItems_Click(object sender, EventArgs e) => diagramControl.CopySelectedItems();

        private void _btnPasteItems_Click(object sender, EventArgs e) => diagramControl.Paste();

        private void _btnCreateObject_Click(object sender, EventArgs e)
        {
            diagramControl.Items.Add(new DiagramShape(BasicShapes.Rectangle, 50, 10, 200, 100));
            diagramControl.Items.Add(new DiagramShape(BasicFlowchartShapes.Subprocess, new Rectangle(50, 50, 150, 100)));
            diagramControl.Items.Add(new DiagramShape(BasicShapes.Decagon, new Rectangle(250, 50, 150, 100)));
            diagramControl.Items.Add(new DiagramShape(ArrowShapes.CurvedLeftArrow, new Rectangle(50, 170, 150, 100)));
            diagramControl.Items.Add(new DiagramShape(DecorativeShapes.Cloud, new Rectangle(250, 170, 150, 100)));
            // 图形模板(Diagram Stencil)
            var descriptions = new List<ShapeDescription>();
            foreach (var a in DiagramToolboxRegistrator.Stencils)
            {
                descriptions.AddRange(a.Shapes.ToList());
            };
            var description = descriptions.First();

            var shape = new DiagramShape(BasicShapes.Rectangle, new Rectangle(200, 100, 200, 150));
            diagramControl.Items.Add(shape);

            //Timer myTimer = new Timer();
            //myTimer.Tick += (sender, e) => {
            //    if (diagramControl.Page == null)
            //    {
            //        myTimer.Stop();
            //        return;
            //    }
            //    shape.Shape = description;
            //    shape.Content = description.Id;
            //    int index = descriptions.IndexOf(description) + 1;
            //    if (index == descriptions.Count)
            //        index = 0;
            //    description = descriptions[index];
            //};
            //myTimer.Interval = 500;
            //myTimer.Start();

        }

        private void _btnDeleteSelected_Click(object sender, EventArgs e)
        {
            diagramControl.DeleteSelectedItems();
        }

        private readonly MemoryStream _memoryStream = new MemoryStream();

        private void _btnSaveToStream_Click(object sender, EventArgs e)
        {
            diagramControl.SaveDocument(_memoryStream);
        }

        private void _btnRestoreFromStream_Click(object sender, EventArgs e)
        {
            if (_memoryStream.Length == 0) { UtilityHelper.ShowInfoMessage("先保存"); return; }
            _memoryStream.Seek(0, SeekOrigin.Begin);
            diagramControl.LoadDocument(_memoryStream);

        }

        private void _btnSaveFile_Click(object sender, EventArgs e)
        {
            diagramControl.SaveFile();
        }

        private void _btnOpenFile_Click(object sender, EventArgs e)
        {
            diagramControl.OpenFile();
        }

        private void _btnDiagramAppearance_Click(object sender, EventArgs e)
        {
            var diagramItem1 = new DiagramShape(BasicShapes.Rectangle, 10, 10, 200, 100) { Content = "Text" };
            diagramControl.Appearance.Shape.Font = new Font("Times New Roman", 40);
            diagramControl.Appearance.Shape.BackColor = Color.Yellow;
            diagramControl.Appearance.Shape.ForeColor = Color.Red;
            diagramControl.Appearance.Shape.BorderColor = Color.Orange;
            diagramControl.Appearance.Shape.BorderSize = 5;

            diagramControl.Items.Add(diagramItem1);
            diagramControl.Items.Add(new DiagramShape(BasicShapes.Rectangle, 10, 150, 200, 100));
            //改变样式

            var diagramShape1 = new DiagramShape(BasicShapes.Rectangle, 10, 150, 200, 100);
            var diagramShape2 = new DiagramShape(BasicShapes.Rectangle, 250, 10, 200, 100);

            diagramShape1.Content = "Text1";
            diagramShape2.Content = "Text2";

            diagramShape1.Appearance.BackColor = Color.Green;
            diagramShape1.Appearance.BorderColor = Color.Orange;
            diagramShape2.Appearance.BorderColor = diagramShape1.Appearance.GetBackColor();
            diagramShape1.Appearance.BorderSize = 5;
            diagramShape2.Appearance.BorderSize = 12;
            diagramShape2.Appearance.Font = new Font("Times New Roman", 20);

            diagramControl.Items.AddRange(diagramShape1, diagramShape2);

            //改变Connector样式
            diagramControl.Appearance.Connector.ForeColor = Color.Red;
            diagramControl.Appearance.Connector.BackColor = Color.Green;

            var diagramShape11 = new DiagramShape(BasicShapes.Rectangle, 50, 50, 50, 50);
            var diagramShape12 = new DiagramShape(BasicShapes.Rectangle, 50, 150, 50, 50);
            var diagramShape13 = new DiagramShape(BasicShapes.Rectangle, 300, 50, 50, 50);
            var diagramShape14 = new DiagramShape(BasicShapes.Rectangle, 300, 150, 50, 50);

            var connector1 = new DiagramConnector(diagramShape11, diagramShape13)
            {
                Content = "Text1",
                CanSelect = true,
                CanDragBeginPoint = false,
                CanDragEndPoint = false
            };

            connector1.Appearance.BackColor = Color.Orange;
            connector1.Appearance.ForeColor = Color.Blue;
            connector1.EndArrow = ArrowDescriptions.Open90;

            var connector2 = new DiagramConnector(diagramShape12, diagramShape14)
            {
                Content = "Text2",
                EndArrow = ArrowDescriptions.Open90
            };

            diagramControl.Items.AddRange(diagramShape11, diagramShape12, diagramShape13, diagramShape14, connector1, connector2);

        }

        private void _btnCheckConnector_Click(object sender, EventArgs e)
        {
            var shapes = diagramControl.Items.OfType<DiagramShape>();
            var diagramShapes = shapes as IList<DiagramShape> ?? shapes.ToList();
            //if (diagramShapes.Any())
            //{
            //    diagramShapes.SafeForEach(shape =>
            //    {

            //    });
            //}
            var connectors = diagramControl.Items.OfType<DiagramConnector>();
            var diagramConnectors = connectors as IList<DiagramConnector> ?? connectors.ToList();
            if (diagramConnectors.Any())
            {
                diagramConnectors.SafeForEach(connector =>
                {
                    if (connector.BeginItem == null || connector.EndItem == null) UtilityHelper.ShowInfoMessage("error");
                });

            }

            if (diagramShapes.Count != diagramConnectors.Count + 1) UtilityHelper.ShowInfoMessage("图形数量比连接数量多1不成立");
        }

        private void _btnExport_Click(object sender, EventArgs e)
        {
            diagramControl.ExportDiagram(DiagramExportFormat.JPEG);
            diagramControl.ExportDiagram(@"D:\流程.jpg", 300, 4);
        }

        private void _bbiPropertyPanelVisiable_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            _sidePanelProperty.Visible = !_sidePanelProperty.Visible;
        }

        private DiagramItemStyle _copyStyle;
        private void _bbiCopyConnectorStyle_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var connector = diagramControl.PrimarySelection;
            var appearance = connector?.Appearance;
            if (appearance == null) return;
            var style = new DiagramItemStyle(
                new DiagramItemBrush(appearance.ForeColor, appearance.BackColor, appearance.BorderColor),
                new DiagramFontSettings(appearance.Font.Size, new FontFamilyInfo(appearance.Font.FontFamily.Name),
                     new DiagramFontEffects(appearance.Font.Bold, appearance.Font.Italic, appearance.Font.Underline, appearance.Font.Strikeout)),
                new DiagramItemLineSettings(connector.Weight, connector.Appearance.BorderDashPattern));
            _copyStyle = style;
        }

        private void _bbiApplyConnectorStyle_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (_copyStyle == null) return;
            var connector = diagramControl.PrimarySelection;
            var appearance = connector?.Appearance;
            if (appearance == null) return;
            appearance.ForeColor = _copyStyle.Brush.Foreground;
            appearance.BackColor = _copyStyle.Brush.Background;
            appearance.BorderColor = _copyStyle.Brush.Stroke;
            //Font样式
            var fontStyle = FontStyle.Regular;
            var fontEffect = _copyStyle.FontSettings.FontEffects;
            if (fontEffect.IsFontBold) fontStyle |= FontStyle.Bold;
            if (fontEffect.IsFontItalic) fontStyle |= FontStyle.Italic;
            if (fontEffect.IsFontStrikethrough) fontStyle |= FontStyle.Strikeout;
            if (fontEffect.IsFontUnderline) fontStyle |= FontStyle.Underline;
            appearance.Font = new Font(new FontFamily(_copyStyle.FontSettings.FontFamily.Name), (float)_copyStyle.FontSettings.FontSize, fontStyle);
            appearance.BorderDashPattern = _copyStyle.LineSettings.StrokeDashArray;
            connector.Weight = (float)_copyStyle.LineSettings.StrokeThickness;

        }

        private void _btnCommandDrag_Click(object sender, EventArgs e)
        {
            diagramControl.DragOver += DiagramControl_DragOver;
            //DiagramHandler.OnToolboxDragItemStart(e);
            var diagramShape1 = new DiagramShape(BasicShapes.Rectangle, 10, 150, 200, 100);
            //diagramControl.Commands().Execute(DiagramCommandsBase.SelectHexagonToolCommand,  new ShapeTool(BasicShapes.Hexagon));
        }

        private void DiagramControl_DragOver(object sender, DragEventArgs e)
        {
            var handler = new DiagramControlHandler(diagramControl);
            DiagramController controller = new DiagramController(diagramControl);

            diagramControl.Commands().Execute(DiagramCommandsBase.StartDragToolCommand, new ShapeTool(BasicShapes.Hexagon));
        }

        private void _btnSetBackground_Click(object sender, EventArgs e)
        {
            FileDialog dialog = new OpenFileDialog();
            var dr = dialog.ShowDialog(this);
            if (dr != DialogResult.OK) return;
            var fileName = dialog.FileName;
            var img = Image.FromFile(fileName);
            diagramControl.BackgroundImage = img;
            //diagramControl.BackgroundImageLayout = ImageLayout.Stretch;
            //diagramControl.Refresh();
        }

        private void DiagramControl_BackgroundImageChanged(object sender, EventArgs e)
        {
            diagramControl.OptionsView.PageMargin=new Padding(0);
            var width = diagramControl.BackgroundImage.Width;
            var height = diagramControl.BackgroundImage.Height;
            diagramControl.OptionsView.PageSize =new SizeF(width,height); ;
            //var g = diagramControl.CreateGraphics();
            //var graphicsState = g.Save();
            //try
            //{
            //    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
            //    g.TranslateTransform(diagramControl.OptionsView.PageMargin.Left, diagramControl.OptionsView.PageMargin.Top);
            //    g.DrawImage(diagramControl.BackgroundImage, new Point(0, 0));
            //}
            //finally
            //{
            //    g.Restore(graphicsState);
            //}
        }

        private void DiagramControl_CustomDrawBackground(object sender, CustomDrawBackgroundEventArgs e)
        {
            if (diagramControl.BackgroundImage == null) return;
            var g = e.Graphics;// diagramControl.CreateGraphics();
            var graphicsState = g.Save();
            try
            {
                //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                //g.TranslateTransform(diagramControl.OptionsView.PageMargin.Left, diagramControl.OptionsView.PageMargin.Top);
                g.DrawImage(diagramControl.BackgroundImage,new Rectangle(0,0,diagramControl.Width,diagramControl.Height));
            }
            finally
            {
                g.Restore(graphicsState);
            }
        }
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Proc. Linn. Soc. N. S. W. 82: 211 (1957)

#### Original name
Asterina randiae-benthamianae Hansf., 1957

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
This is [itamae](https://github.com/itamae-kitchen/itamae) plugin that provides store for secrets, like encrypted data bag in chef.

## Installation

```ruby
gem 'itamae-secrets'
```

or

```
$ gem install itamae-secrets
```

## Basic

- `itamae-secrets` command for storing data or manually reading
- `Itamae::Secrets` interface for itamae recipes
- Data are stored in _base directory._
  - You must avoid `${base}/keys` from checked into VCS. (`.gitignore` it!)

## Walkthrough

### Generate a key

##### randomly

```
$ itamae-secrets newkey --base=./secret --method=aes-random
```

##### from passphrase

```
$ itamae-secrets newkey --base=./secret --method=aes-passphrase
```

Both generates `./secret/keys/default`. Make sure `./secret/keys` be excluded from VCS.

### Store value

```
$ itamae-secrets set --base=./secret awesome_secret value
```

(when omit `value`, it'll read from STDIN until EOF. You can also use `--noecho` if you want hide value in your terminal's buffer completely.)

### Reading data from itamae

on your itamae recipe, do:

``` ruby
require 'itamae/secrets'
node[:secrets] = Itamae::Secrets(File.join(__dir__, 'secrets'))

# Use it
p node[:secrets][:awesome_secret]
```

### Reading data fro CLI

```
$ itamae-secrets get --base=./secret awesome_secret
```

### Remembering `--base`

```
$ echo 'base: ./secret' >> .itamae-secrets.yml
```

## Development

After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake rspec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).

## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/sorah/itamae-secrets.

__Security issues?__ Send me directly at `security@sorah.jp`. My GPG key is available here: <http://sorah.jp/id.html> ([SSL](https://github.com/sorah/sorah.jp/tree/master/source/pgp-pubkeys))

## License

The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).

## To-dos

- [ ] Missing test :(


text:
<?php

namespace Wallabag\CoreBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\RulerZ\Validator\Constraints as RulerZAssert;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Ignore Origin rule.
 *
 * @ORM\Entity(repositoryClass="Wallabag\CoreBundle\Repository\IgnoreOriginUserRuleRepository")
 * @ORM\Table(name="`ignore_origin_user_rule`")
 */
class IgnoreOriginUserRule implements IgnoreOriginRuleInterface, RuleInterface
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @Assert\NotBlank()
     * @Assert\Length(max=255)
     * @RulerZAssert\ValidRule(
     *  allowed_variables={"host","_all"},
     *  allowed_operators={"=","~"}
     * )
     * @ORM\Column(name="rule", type="string", nullable=false)
     */
    private $rule;

    /**
     * @ORM\ManyToOne(targetEntity="Wallabag\CoreBundle\Entity\Config", inversedBy="ignoreOriginRules")
     */
    private $config;

    /**
     * Get id.
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set rule.
     *
     * @return IgnoreOriginRuleInterface
     */
    public function setRule(string $rule)
    {
        $this->rule = $rule;

        return $this;
    }

    /**
     * Get rule.
     *
     * @return string
     */
    public function getRule()
    {
        return $this->rule;
    }

    /**
     * Set config.
     *
     * @return IgnoreOriginUserRule
     */
    public function setConfig(Config $config)
    {
        $this->config = $config;

        return $this;
    }

    /**
     * Get config.
     *
     * @return Config
     */
    public function getConfig()
    {
        return $this->config;
    }
}


text:
using System;
using System.IO;
using Xunit;

namespace System.IO.Tests
{
    public class FileStream_Seek : FileSystemTest
    {
        [Fact]
        public void InvalidSeekOriginThrows()
        {
            using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
            {
                Assert.Throws<ArgumentException>("origin", () => fs.Seek(0, ~SeekOrigin.Begin));
            }
        }

        [Fact]
        public void InvalidOffsetThrows()
        {
            using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
            {
                // Ensure our test is set up correctly
                Assert.Equal(0, fs.Length);
                Assert.Equal(0, fs.Position);

                Assert.Throws<IOException>(() => fs.Seek(-1, SeekOrigin.Begin));
                Assert.Throws<IOException>(() => fs.Seek(-1, SeekOrigin.Current));
                Assert.Throws<IOException>(() => fs.Seek(-1, SeekOrigin.End));

                Assert.Throws<IOException>(() => fs.Seek(int.MinValue, SeekOrigin.Begin));
                Assert.Throws<IOException>(() => fs.Seek(int.MinValue, SeekOrigin.Current));
                Assert.Throws<IOException>(() => fs.Seek(int.MinValue, SeekOrigin.End));
            }
        }

        [Fact]
        public void SeekDisposedThrows()
        {
            using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
            {
                fs.Dispose();
                Assert.Throws<ObjectDisposedException>(() => fs.Seek(1, SeekOrigin.Begin));
                // no fast path
                Assert.Throws<ObjectDisposedException>(() => fs.Seek(fs.Position, SeekOrigin.Begin));
                // parameter checking happens first
                Assert.Throws<ArgumentException>("origin", () => fs.Seek(0, ~SeekOrigin.Begin));
            }
        }

        [Fact]
        public void SeekUnseekableThrows()
        {
            using (FileStream fs = new UnseekableFileStream(GetTestFilePath(), FileMode.Create))
            {
                Assert.Throws<NotSupportedException>(() => fs.Seek(1, SeekOrigin.Begin));
                // no fast path
                Assert.Throws<NotSupportedException>(() => fs.Seek(fs.Position, SeekOrigin.Begin));
                // parameter checking happens first
                Assert.Throws<ArgumentException>("origin", () => fs.Seek(0, ~SeekOrigin.Begin));
                // dispose checking happens first
                fs.Dispose();
                Assert.Throws<ObjectDisposedException>(() => fs.Seek(fs.Position, SeekOrigin.Begin));
            }
        }

        [Fact]
        public void SeekAppendModifyThrows()
        {
            string fileName = GetTestFilePath();
            using (FileStream fs = new FileStream(fileName, FileMode.Create))
            {
                fs.Write(TestBuffer, 0, TestBuffer.Length);
            }

            using (FileStream fs = new FileStream(fileName, FileMode.Append))
            {
                long length = fs.Length;
                Assert.Throws<IOException>(() => fs.Seek(length - 1, SeekOrigin.Begin));
                Assert.Equal(length, fs.Position);
                Assert.Throws<IOException>(() => fs.Seek(-1, SeekOrigin.Current));
                Assert.Equal(length, fs.Position);
                Assert.Throws<IOException>(() => fs.Seek(-1, SeekOrigin.End));
                Assert.Equal(length, fs.Position);

                Assert.Throws<IOException>(() => fs.Seek(0, SeekOrigin.Begin));
                Assert.Equal(length, fs.Position);
                Assert.Throws<IOException>(() => fs.Seek(-length, SeekOrigin.Current));
                Assert.Equal(length, fs.Position);
                Assert.Throws<IOException>(() => fs.Seek(-length, SeekOrigin.End));
                Assert.Equal(length, fs.Position);
            }
        }

        [Fact]
        public void SeekOriginBegin()
        {
            using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
            {
                fs.Write(TestBuffer, 0, TestBuffer.Length);

                // Ensure our test is set up correctly
                Assert.Equal(TestBuffer.Length, fs.Length);
                Assert.Equal(TestBuffer.Length, fs.Position);

                // Beginning
                Assert.Equal(0, fs.Seek(0, SeekOrigin.Begin));
                Assert.Equal(0, fs.Position);

                // End
                Assert.Equal(fs.Length, fs.Seek(fs.Length, SeekOrigin.Begin));
                Assert.Equal(fs.Length, fs.Position);

                // Middle
                Assert.Equal(fs.Length / 2, fs.Seek(fs.Length / 2, SeekOrigin.Begin));
                Assert.Equal(fs.Length / 2, fs.Position);
            }
        }

        [Fact]
        public void SeekOriginCurrent()
        {
            using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
            {
                fs.Write(TestBuffer, 0, TestBuffer.Length);

                // Ensure our test is set up correctly
                Assert.Equal(TestBuffer.Length, fs.Length);
                Assert.Equal(TestBuffer.Length, fs.Position);

                // Beginning
                Assert.Equal(0, fs.Seek(-fs.Length, SeekOrigin.Current));
                Assert.Equal(0, fs.Position);

                // End
                Assert.Equal(fs.Length, fs.Seek(fs.Length, SeekOrigin.Current));
                Assert.Equal(fs.Length, fs.Position);

                // Middle
                Assert.Equal(fs.Length / 2, fs.Seek(fs.Length / 2 - fs.Length, SeekOrigin.Current));
                Assert.Equal(fs.Length / 2, fs.Position);
            }
        }

        [Fact]
        public void SeekOriginEnd()
        {
            using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
            {
                fs.Write(TestBuffer, 0, TestBuffer.Length);

                // Ensure our test is set up correctly
                Assert.Equal(TestBuffer.Length, fs.Length);
                Assert.Equal(TestBuffer.Length, fs.Position);

                // Beginning
                Assert.Equal(0, fs.Seek(-fs.Length, SeekOrigin.End));
                Assert.Equal(0, fs.Position);

                // End
                Assert.Equal(fs.Length, fs.Seek(0, SeekOrigin.End));
                Assert.Equal(fs.Length, fs.Position);

                // Middle
                Assert.Equal(fs.Length / 2, fs.Seek(fs.Length / 2 - fs.Length, SeekOrigin.End));
                Assert.Equal(fs.Length / 2, fs.Position);
            }
        }

        [Fact]
        public void NoopSeeksDoNotChangePosition()
        {
            using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
            {
                fs.Write(TestBuffer, 0, TestBuffer.Length);

                // Ensure our test is set up correctly
                Assert.Equal(TestBuffer.Length, fs.Length);
                Assert.Equal(TestBuffer.Length, fs.Position);

                // end
                ValidateNoopSeeks(fs);

                fs.Seek(0, SeekOrigin.Begin);

                // beginning
                ValidateNoopSeeks(fs);

                fs.Seek(fs.Length / 2, SeekOrigin.Begin);

                // middle
                ValidateNoopSeeks(fs);
            }
        }

        private void ValidateNoopSeeks(Stream stream)
        {
            // validate seeks that don't change position
            long position = stream.Position;

            Assert.Equal(position, stream.Seek(position, SeekOrigin.Begin));
            Assert.Equal(position, stream.Position);

            Assert.Equal(position, stream.Seek(0, SeekOrigin.Current));
            Assert.Equal(position, stream.Position);

            Assert.Equal(position, stream.Seek(position - stream.Length, SeekOrigin.End));
            Assert.Equal(position, stream.Position);
        }

        [Fact]
        public void SeekPastEnd()
        {
            using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
            {
                fs.Write(TestBuffer, 0, TestBuffer.Length);

                // Ensure our test is set up correctly
                Assert.Equal(TestBuffer.Length, fs.Length);
                Assert.Equal(TestBuffer.Length, fs.Position);
                long originalLength = TestBuffer.Length;

                // Move past end
                Assert.Equal(originalLength + 1, fs.Seek(fs.Length + 1, SeekOrigin.Begin));
                Assert.Equal(originalLength + 1, fs.Position);
                // Length is not updated until a write
                Assert.Equal(originalLength, fs.Length);

                // At end of stream
                Assert.Equal(-1, fs.ReadByte());
                // Read should not update position or length
                Assert.Equal(originalLength + 1, fs.Position);
                Assert.Equal(originalLength, fs.Length);

                // Move back one, still at end of stream since length hasn't changed
                Assert.Equal(originalLength, fs.Seek(-1, SeekOrigin.Current));
                Assert.Equal(-1, fs.ReadByte());
                // Read should not update position or length
                Assert.Equal(originalLength, fs.Position);
                Assert.Equal(originalLength, fs.Length);

                // Move past end
                Assert.Equal(originalLength + 1, fs.Seek(fs.Length + 1, SeekOrigin.Begin));
                fs.WriteByte(0x2A);
                // Writing a single byte should update length by 2 (filling gap with zero).
                Assert.Equal(originalLength + 2, fs.Position);
                Assert.Equal(originalLength + 2, fs.Length);
                // Validate zero fill
                Assert.Equal(originalLength, fs.Seek(-2, SeekOrigin.Current));
                Assert.Equal(0, fs.ReadByte());
                // Validate written value
                Assert.Equal(0x2A, fs.ReadByte());
            }
        }

        [Fact]
        public void RandomSeekReadConsistency()
        {
            using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
            {
                var rand = new Random(1); // fixed seed to enable repeatable runs
                const int Trials = 1000;
                const int FileLength = 0x4000;
                const int MaxBytesToRead = 21;

                // Write data to the file
                var buffer = new byte[FileLength];
                for (int i = 0; i < buffer.Length; i++)
                    buffer[i] = (byte)i;
                fs.Write(buffer, 0, buffer.Length);
                fs.Position = 0;

                // Repeatedly jump around, reading, and making sure we get the right data back
                for (int trial = 0; trial < Trials; trial++)
                {
                    // Pick some number of bytes to read
                    int bytesToRead = rand.Next(1, MaxBytesToRead);

                    // Jump to a random position, seeking either from one of the possible origins
                    SeekOrigin origin = (SeekOrigin)rand.Next(3);
                    int offset = 0;
                    switch (origin)
                    {
                        case SeekOrigin.Begin:
                            offset = rand.Next(0, (int)fs.Length - bytesToRead);
                            break;
                        case SeekOrigin.Current:
                            offset = rand.Next(-(int)fs.Position + bytesToRead, (int)fs.Length - (int)fs.Position - bytesToRead);
                            break;
                        case SeekOrigin.End:
                            offset = -rand.Next(bytesToRead, (int)fs.Length);
                            break;
                    }
                    long pos = fs.Seek(offset, origin);
                    Assert.InRange(pos, 0, fs.Length - bytesToRead - 1);

                    // Read the requested number of bytes, and verify each is correct
                    for (int i = 0; i < bytesToRead; i++)
                    {
                        int byteRead = fs.ReadByte();
                        Assert.Equal(buffer[pos + i], byteRead);
                    }
                }
            }
        }

    }
}


text:
	<title>Fred Talbot's panel show appearances</title>

	<link rel="stylesheet" media="all" href="../style.css" type="text/css"/>

Fred Talbot's panel show appearances

Fred Talbot (born 1949-12-17[ref]) has appeared in 1 episodes between 1996-1996.  Fred Talbot on IMDB. Fred Talbot on Wikipedia.

1996

1996-11-29 / Shooting Stars


text:
<?php

namespace Deployer\Log;

class Message
{

    private $type;
    private $message;

    public function __construct($type, $message)
    {
        $this->setType($type)
            ->setMessage($message);
    }

    public function getType(): string
    {
        return $this->type;
    }

    public function getTypeShort(): string
    {
        return substr($this->getType(), 0, 3);
    }

    public function getMessage(): string
    {
        return $this->message;
    }

    private function setType(string $type)
    {
        $this->type = $type;

        return $this;
    }

    private function setMessage(string $message)
    {
        $this->message = $message;

        return $this;
    }

    public function is(string $type): bool
    {
        return $this->getType() === $type;
    }

    public function print()
    {
        echo $this->formatted();
    }

    public function log()
    {
        file_put_contents('deployer.log', $this->getDate(). ' - ' . $this->formatted(), FILE_APPEND);
    }

    public function formatted()
    {
        return strtoupper($this->getTypeShort()) . ': ' . $this->getMessage() . PHP_EOL;
    }

    private function getDate()
    {
        return date('Y-m-d H:i:s');
    }

}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Ants.Web;
using NUnit.Framework;
using Owin;

namespace Ants.Tests
{
    [TestFixture]
    public class TestOwin
    {
        [Ignore("Experimental feature that is not ready."), Test]
        public async Task Test()
        {
            TestHelper.EnsureNothingIsRunning();

            AspNetTestServer.Start<Global>(new StartApplicationArgs
            {
                PhysicalDirectory = TestHelper.WebProjectDirectory
            });

            TestHelper.EnsureServerStarted();

            using (var client = AspNetTestServer.GetHttpClient<Global>())
            {
                using (var request = new HttpRequestMessage(HttpMethod.Get, "/owin/test"))
                using (var result = await client.SendAsync(request).ConfigureAwait(false))
                {
                    Assert.IsNotNull(result);
                    Assert.IsNotNull(result.Content);

                    Assert.AreEqual(result.StatusCode, HttpStatusCode.OK);

                    Debug.WriteLine(result);

                    foreach (var stage in Enum.GetValues(typeof(PipelineStage))
                        .Cast<int>()
                        .OrderBy(value => value)
                        .Cast<PipelineStage>())
                    {
                        //todo: map handler via owin is not currently supported over ANTS
                        if (stage == PipelineStage.MapHandler)
                        {
                            continue;
                        }

                        Assert.IsTrue(result.Headers.TryGetValues($"Owin-{stage}", out IEnumerable<string> values));
                        Assert.IsNotNull(values);

                        var valueStr = values.FirstOrDefault();
                        Assert.IsTrue(int.TryParse(valueStr, out int value));

                        Assert.AreEqual((int) stage, value);
                    }
                }
            }

            await AspNetTestServer.Stop<Global>().ConfigureAwait(false);

            TestHelper.EnsureServerStopped();
        }
    }
}


text:
import path from 'path'
import webpack from 'webpack'

// Browsers to run on BrowserStack.
const CUSTOM_LAUNCHERS = {
  BS_Chrome: {
    base: 'BrowserStack',
    os: 'Windows',
    os_version: '8.1',
    browser: 'chrome',
    browser_version: '39.0'
  },
  BS_Firefox: {
    base: 'BrowserStack',
    os: 'Windows',
    os_version: '8.1',
    browser: 'firefox',
    browser_version: '32.0'
  },
  BS_Safari: {
    base: 'BrowserStack',
    os: 'OS X',
    os_version: 'Yosemite',
    browser: 'safari',
    browser_version: '8.0'
  },
  BS_MobileSafari: {
    base: 'BrowserStack',
    os: 'ios',
    os_version: '7.0',
    browser: 'iphone',
    real_mobile: false
  },
//  BS_InternetExplorer9: {
//    base: 'BrowserStack',
//    os: 'Windows',
//    os_version: '7',
//    browser: 'ie',
//    browser_version: '9.0'
//  },
  BS_InternetExplorer10: {
    base: 'BrowserStack',
    os: 'Windows',
    os_version: '8',
    browser: 'ie',
    browser_version: '10.0'
  },
  BS_InternetExplorer11: {
    base: 'BrowserStack',
    os: 'Windows',
    os_version: '8.1',
    browser: 'ie',
    browser_version: '11.0'
  }
}

function setBrowserStack(config, project) {
  const { env } = process

  if (env.USE_CLOUD) {
    config.set({
      customLaunchers: CUSTOM_LAUNCHERS,
      browsers: Object.keys(CUSTOM_LAUNCHERS),
      reporters: [ 'dots', 'coverage' ],
      browserDisconnectTimeout: 10000,
      browserDisconnectTolerance: 3,
      browserNoActivityTimeout: 30000,
      captureTimeout: 120000,
      browserStack: {
        username: env.BROWSER_STACK_USERNAME,
        accessKey: env.BROWSER_STACK_ACCESS_KEY,
        pollingTimeout: 10000,
        startTunnel: true
      }
    })

    if (env.TRAVIS) {
      Object.assign(config.browserStack, {
        startTunnel: false,
        project,
        build: `TRAVIS #${env.TRAVIS_BUILD_NUMBER} (${env.TRAVIS_BUILD_ID})`,
        name: env.TRAVIS_JOB_NUMBER
      })
    }
  }
}

export default config => {
  const { env } = process

  const isCi = env.CONTINUOUS_INTEGRATION === 'true'
  const runCoverage = env.COVERAGE === 'true' || isCi

  const coverageLoaders = []
  const coverageReporters = []

  if (runCoverage) {
    coverageLoaders.push({
      test: /\.js$/,
      include: path.resolve('modules/'),
      exclude: /__tests__/,
      loader: 'isparta'
    })

    coverageReporters.push('coverage')
  }

  config.set({
    frameworks: [ 'mocha' ],

    files: [ 'tests.webpack.js' ],

    preprocessors: {
      'tests.webpack.js': [ 'webpack', 'sourcemap' ]
    },

    webpack: {
      module: {
        loaders: [
          { test: /\.js$/, exclude: /node_modules/, loader: 'babel' },
          ...coverageLoaders
        ]
      },
      plugins: [
        new webpack.DefinePlugin({
          'process.env.NODE_ENV': JSON.stringify('test')
        })
      ],
      devtool: 'inline-source-map'
    },

    webpackMiddleware: {
      noInfo: true
    },

    reporters: [ 'mocha', ...coverageReporters ],

    coverageReporter: {
      reporters: [
        { type: 'html', subdir: 'html' },
        { type: 'lcovonly', subdir: '.' }
      ]
    },

    browsers: [ 'Chrome' ],

    singleRun: isCi
  })

  setBrowserStack(config, 'react-router')
}


text:
'use strict';

describe('Controller: AutoCtrl', function () {

  // load the controller's module
  beforeEach(module('mydieselmechanicApp'));

  var AutoCtrl, scope;

  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller, $rootScope) {
    scope = $rootScope.$new();
    AutoCtrl = $controller('AutoCtrl', {
      $scope: scope
    });
  }));

  it('should ...', function () {
    expect(1).toEqual(1);
  });
});


text:
package com.mqvisualizer.ui;

import com.mqvisualizer.core.config.JmsConnectionsConfigManager;
import com.mqvisualizer.core.config.JmsProvidersConfigManager;
import com.mqvisualizer.core.connection.JmsConnectionsViewModel;
import com.mqvisualizer.core.provider.JmsProvidersViewModel;
import com.mqvisualizer.ui.connection.treeview.JmsConnectionsTreeView;
import com.mqvisualizer.ui.destination.tab.JmsTabPane;
import com.mqvisualizer.ui.icon.Icon;
import javafx.application.Application;
import javafx.geometry.Orientation;
import javafx.scene.Scene;
import javafx.scene.control.SplitPane;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;

/**
 * Created by Mykolas on 2014-08-19.
 */
public class MqVisualizerApplication extends Application {

    public MqVisualizerApplication() {
        try {
            JmsConnectionsConfigManager.getInstance();
            JmsProvidersViewModel.getInstance();
            JmsConnectionsViewModel.getInstance().loadConnections();
        } catch (Exception e) {
            new ErrorDialog(e.getMessage(), e).show();
            throw e;
        }
    }

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) throws Exception {
        JmsTabPane destinationsTabPane = new JmsTabPane();
        JmsConnectionsTreeView treeView = new JmsConnectionsTreeView(
                JmsConnectionsViewModel.getInstance().getConnectionViewModels(),
                destinationsTabPane
        );

        AnchorPane leftPane = new AnchorPane();
        AnchorPane.setBottomAnchor(treeView, 0.0);
        AnchorPane.setLeftAnchor(treeView, 0.0);
        AnchorPane.setRightAnchor(treeView, 0.0);
        AnchorPane.setTopAnchor(treeView, 0.0);
        leftPane.getChildren().add(treeView);

        AnchorPane centerPane = new AnchorPane();
        AnchorPane.setBottomAnchor(destinationsTabPane, 0.0);
        AnchorPane.setLeftAnchor(destinationsTabPane, 0.0);
        AnchorPane.setRightAnchor(destinationsTabPane, 0.0);
        AnchorPane.setTopAnchor(destinationsTabPane, 0.0);
        centerPane.getChildren().add(destinationsTabPane);

        SplitPane splitPane = new SplitPane();
        splitPane.setOrientation(Orientation.HORIZONTAL);
        splitPane.setPrefHeight(600);
        splitPane.setPrefWidth(1000);
        splitPane.setDividerPositions(0.3);
        splitPane.getItems().add(leftPane);
        splitPane.getItems().add(centerPane);

        Scene scene = new Scene(splitPane);

        stage.getIcons().addAll(
                Icon.CONNECTION_16.getImageView().getImage(),
                Icon.CONNECTION_32.getImageView().getImage(),
                Icon.CONNECTION_48.getImageView().getImage(),
                Icon.CONNECTION_64.getImageView().getImage(),
                Icon.CONNECTION_128.getImageView().getImage(),
                Icon.CONNECTION_256.getImageView().getImage()
        );
        stage.setTitle("mqvisualizer");
        stage.setScene(scene);
        stage.setMaximized(true);
        stage.show();

        splitPane.setDividerPositions(0.3);
    }

    @Override
    public void stop() throws Exception {
        JmsConnectionsViewModel.getInstance().disconnectAll();
    }
}


text:
"""
This modudle handles CRUD for Recipe Categories and Recipes
"""
CATEGORIES = {}

class Categories(object):
    """This class contains the CRUD features for Categories"""

    def __init__(self):
        """Initialize objects of this class with the following"""
        self.name = ''
        self.description = ''
        self.owner = ''
        self.recipes = {}

    def add_category(self, name, description, owner):
        """Add to categories list"""
        self.name = name
        self.description = description
        if self.name in CATEGORIES:
            return "Sorry. Category already exists"
        CATEGORIES[name] = {
            "name": self.name,
            "description": self.description,
            "recipes": self.recipes,
            "owner": owner
        }
        return CATEGORIES[name]

    def get_category(self, name, owner):
        """Returns the named category or error message"""
        if name in CATEGORIES and CATEGORIES[name]['owner'] == owner:
            return CATEGORIES[name]
        return "Category does not exist."

    def set_category(self, name, description, owner):
        """Returns the updated category or error message"""
        if name in CATEGORIES:
            CATEGORIES[name] = {
                "name": name,
                "description": description,
                'owner': owner,
                'recipes': CATEGORIES[name]['recipes']
            }
            return CATEGORIES[name]
        return "Category does not exist."

    def delete_category(self, name, owner):
        """Deletes a category and returns confirmation or error"""
        if name in CATEGORIES and CATEGORIES[name]['owner'] == owner:
            CATEGORIES.pop(name)
            return "Removed successfully."
        return "Category does not exist."

class Recipes(object):
    """
    This class contains the CRUD features for recipes
    """

    def __init__(self):
        """Default constructor"""

    def add_recipe(self, category, recipe):
        """Add a new recipe only to existing categories"""
        if category in CATEGORIES:
            CATEGORIES[category]['recipes'][recipe['name']] = recipe
            return "Recipe added successfully."
        return "Category does not exist."

    def get_recipe(self, category, name):
        """Get the recipe from the spefied category"""
        if category not in CATEGORIES:
            return "Recipe does not exist"
        if name in CATEGORIES[category]['recipes']:
            recipe = CATEGORIES[category]['recipes'][name]
            return recipe
        return "Recipe does not exist"

    def set_recipe(self, category, name, content):
        """Get the recipe from the spefied category"""
        if category not in CATEGORIES:
            return "Recipe does not exist"
        if name in CATEGORIES[category]['recipes']:
            CATEGORIES[category]['recipes'][name].update(content)
            temp_recipe = CATEGORIES[category]['recipes'].pop(name)
            CATEGORIES[category]['recipes'][temp_recipe['name']] = temp_recipe
            return CATEGORIES[category]['recipes']
        return "Recipe does not exist"

    def delete_recipe(self, category, name):
        """Removes the named recipe in the category provided"""
        if category in CATEGORIES and name in CATEGORIES[category]['recipes']:
            CATEGORIES[category]['recipes'].pop(name)
            return "Recipe deleted successfully!"
        return "Recipe does not exist!"


text:
using System;
using System.Threading.Tasks;
using MatterHackers.DataConverters3D;

namespace MatterHackers.MatterControl.Library
{
	public class DynamicContentStore : IContentStore
	{
		private Func<ILibraryItem, IObject3D, Task> saveAction;

		public DynamicContentStore(Func<ILibraryItem, IObject3D, Task> saveAction)
		{
			this.saveAction = saveAction;
		}

        public void Dispose()
        {
        }

        public Task Save(ILibraryItem item, IObject3D content)
		{
			return saveAction.Invoke(item, content);
		}
	}
}


text:
.class public abstract Lcom/samsung/android/hardware/context/ISemContextCallback$Stub;
.super Landroid/os/Binder;
.source "ISemContextCallback.java"

# interfaces
.implements Lcom/samsung/android/hardware/context/ISemContextCallback;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/samsung/android/hardware/context/ISemContextCallback;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x409
    name = "Stub"
.end annotation

.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Lcom/samsung/android/hardware/context/ISemContextCallback$Stub$Proxy;
    }
.end annotation

# static fields
.field private static final DESCRIPTOR:Ljava/lang/String; = "com.samsung.android.hardware.context.ISemContextCallback"

.field static final TRANSACTION_getListenerInfo:I = 0x2

.field static final TRANSACTION_semContextCallback:I = 0x1

# direct methods
.method public constructor <init>()V
    .locals 1

    invoke-direct {p0}, Landroid/os/Binder;-><init>()V

    const-string/jumbo v0, "com.samsung.android.hardware.context.ISemContextCallback"

    invoke-virtual {p0, p0, v0}, Lcom/samsung/android/hardware/context/ISemContextCallback$Stub;->attachInterface(Landroid/os/IInterface;Ljava/lang/String;)V

    return-void
.end method

.method public static asInterface(Landroid/os/IBinder;)Lcom/samsung/android/hardware/context/ISemContextCallback;
    .locals 2

    const/4 v1, 0x0

    if-nez p0, :cond_0

    return-object v1

    :cond_0
    const-string/jumbo v1, "com.samsung.android.hardware.context.ISemContextCallback"

    invoke-interface {p0, v1}, Landroid/os/IBinder;->queryLocalInterface(Ljava/lang/String;)Landroid/os/IInterface;

    move-result-object v0

    if-eqz v0, :cond_1

    instance-of v1, v0, Lcom/samsung/android/hardware/context/ISemContextCallback;

    if-eqz v1, :cond_1

    check-cast v0, Lcom/samsung/android/hardware/context/ISemContextCallback;

    return-object v0

    :cond_1
    new-instance v1, Lcom/samsung/android/hardware/context/ISemContextCallback$Stub$Proxy;

    invoke-direct {v1, p0}, Lcom/samsung/android/hardware/context/ISemContextCallback$Stub$Proxy;-><init>(Landroid/os/IBinder;)V

    return-object v1
.end method

# virtual methods
.method public asBinder()Landroid/os/IBinder;
    .locals 0

    return-object p0
.end method

.method public onTransact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z
    .locals 4
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    const/4 v3, 0x1

    sparse-switch p1, :sswitch_data_0

    invoke-super {p0, p1, p2, p3, p4}, Landroid/os/Binder;->onTransact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z

    move-result v2

    return v2

    :sswitch_0
    const-string/jumbo v2, "com.samsung.android.hardware.context.ISemContextCallback"

    invoke-virtual {p3, v2}, Landroid/os/Parcel;->writeString(Ljava/lang/String;)V

    return v3

    :sswitch_1
    const-string/jumbo v2, "com.samsung.android.hardware.context.ISemContextCallback"

    invoke-virtual {p2, v2}, Landroid/os/Parcel;->enforceInterface(Ljava/lang/String;)V

    invoke-virtual {p2}, Landroid/os/Parcel;->readInt()I

    move-result v2

    if-eqz v2, :cond_0

    sget-object v2, Lcom/samsung/android/hardware/context/SemContextEvent;->CREATOR:Landroid/os/Parcelable$Creator;

    invoke-interface {v2, p2}, Landroid/os/Parcelable$Creator;->createFromParcel(Landroid/os/Parcel;)Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Lcom/samsung/android/hardware/context/SemContextEvent;

    :goto_0
    invoke-virtual {p0, v0}, Lcom/samsung/android/hardware/context/ISemContextCallback$Stub;->semContextCallback(Lcom/samsung/android/hardware/context/SemContextEvent;)V

    invoke-virtual {p3}, Landroid/os/Parcel;->writeNoException()V

    return v3

    :cond_0
    const/4 v0, 0x0

    goto :goto_0

    :sswitch_2
    const-string/jumbo v2, "com.samsung.android.hardware.context.ISemContextCallback"

    invoke-virtual {p2, v2}, Landroid/os/Parcel;->enforceInterface(Ljava/lang/String;)V

    invoke-virtual {p0}, Lcom/samsung/android/hardware/context/ISemContextCallback$Stub;->getListenerInfo()Ljava/lang/String;

    move-result-object v1

    invoke-virtual {p3}, Landroid/os/Parcel;->writeNoException()V

    invoke-virtual {p3, v1}, Landroid/os/Parcel;->writeString(Ljava/lang/String;)V

    return v3

    :sswitch_data_0
    .sparse-switch
        0x1 -> :sswitch_1
        0x2 -> :sswitch_2
        0x5f4e5446 -> :sswitch_0
    .end sparse-switch
.end method


text:
<bill session="111" type="hr" number="162" updated="2009-03-07T13:25:23-05:00">
	<status><introduced date="1234328400" datetime="2009-02-11"/></status>

	<introduced date="1234328400" datetime="2009-02-11"/>
	<titles>
		<title type="official" as="introduced">Providing amounts for the expenses of the Committee on Ways and Means in the One Hundred Eleventh Congress.</title>
	</titles>
	<sponsor id="400333"/>
	<cosponsors>
		<cosponsor id="400058" joined="2009-02-11"/>
	</cosponsors>
	<actions>
		<action date="1234328400" datetime="2009-02-11"><text>Referred to the House Committee on House Administration.</text></action>
	</actions>
	<committees>
		<committee name="House Administration" subcommittee="" activity="Referral, In Committee" />
	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>
	<summary>

	</summary>
</bill>


text:
extern NSString * const kJavaHomeDefaultsKey;
extern NSString * const kMavenHomeDefaultsKey;

extern NSString * const kUseDefaultJavaLocationKey;
extern NSString * const kUseDefaultMavenLocationKey;

@interface MBPreferencesWindowController : NSWindowController

@property (weak) IBOutlet NSButton *mavenDefaultLocation;
@property (weak) IBOutlet NSTextField *mavenLocation;
@property (weak) IBOutlet NSTextField *mavenVersion;

@property (weak) IBOutlet NSButton *javaDefaultLocation;
@property (weak) IBOutlet NSTextField *javaLocation;
@property (weak) IBOutlet NSTextField *javaVersion;

@property (weak) IBOutlet NSProgressIndicator *progressIndicator;

- (IBAction)selectMavenLocationDidPress:(id)sender;
- (IBAction)selectJavaLocationDidPress:(id)sender;

- (IBAction)useMavenDefaultLocationDidPress:(id)sender;
- (IBAction)useJavaDefaultLocationDidPress:(id)sender;

// initializes window with correct NIB name (no other init method should be used)
- (id)init;

@end


text:
using Bolognese.Common.Pomodoro;
using Caliburn.Micro;
using System.Media;

namespace Bolognese.Desktop
{
    public class Alerter : IHandle<SegmentStatusChanged>
    {
        readonly IEventAggregator _events;
        readonly SoundPlayer _player;

        public Alerter(IEventAggregator events)
        {
            _events = events;
            _events.Subscribe(this);
            _player = new SoundPlayer(Properties.Resources.SegmentCompleteAlert);
        }

        void PlayAlert()
        {
            _player.Play();
        }

        void IHandle<SegmentStatusChanged>.Handle(SegmentStatusChanged message)
        {
            if (message.Status == SegmentStatus.Complete)
            {
                PlayAlert();
            }
        }
    }
}


text:
var observable = require("data/observable");
var globalConstants = require("~/common/global-constants");
var Everlive = require('~/everlive.all.min');
var el = new Everlive(globalConstants.ApiId);
var connection = require("~/common/internet-connection");
var playerService = require("~/services/player-service");
var questionService = require("~/services/question-service");

var GameModel = (function (_super) {
  __extends(GameModel, _super);
  function GameModel() {
    _super.call(this);
    this.questionTimer = 10;
    this.turnCol = 0;

    questionService.Question.deleteDataFromTable('Question');
    questionService.Question.seedQuestions();

    var players = playerService.Players.getPlayers();
    var that = this;

    players.then(function(data) {
      that.redPlayer = {name: data[0][1], score: 0, turn: false, country: "Bulgaria"};
      that.bluePlayer = {name: data[1][1], score: 0, turn: false, country: "Bulgaria"};
    });

    this.timerImageSrc = "~/images/timer/timer-10.png";

    if (connection.networkType === 'none') {
      questionService.Question.getAllQuestions().then(function(data) {
        var questionsSQLite = [];

          for (var i = 0; i < data.length; i += 1) {
            var question = {
              questionContent: data[i][1],
              answerA: data[i][2],
              answerB: data[i][3],
              answerC: data[i][4],
              answerD: data[i][5],
              correctAnswer: data[i][6],
              hint: data[i][7]
            };

            questionsSQLite.push(question);
          }

          that.allQuestions = questionsSQLite;
      });

      console.log('Connection type: none');
    } else if (connection.networkType === 'wifi'|| connection.networkType === 'mobile') {
      var questions = el.data('Question');

      that.allQuestions = questions.get().then(function(data) {
        return data.result;
      }, function(error){
        console.log(error);
      });

      console.log('Connecion type: wifi/mobile');
    }
  }
  return GameModel;
})(observable.Observable);

exports.gameViewModel = new GameModel();


text:
import time
import sys

import requests

from ..__init__ import __version__
from .card import ScryfallCard
from .set import ScryfallSet

class Scryfall:

    class APIError(Exception):
        pass

    class TooManyRequests(Exception):
        pass

    API_URL = "https://api.scryfall.com"
    USER_AGENT = (
        "scrycli/{} (github.com/polarpayne/scrycli) "
        "requests/{} "
        "python/{}.{}.{}"
    ).format(
        __version__,
        requests.__version__,
        sys.version_info.major,
        sys.version_info.minor,
        sys.version_info.micro
    )
    SLEEP = 0.1

    def __init__(self, isatty=False, urls=False):
        self.card_kwargs = {
            "isatty": isatty,
            "urls": urls
        }

        self._r = requests.session()
        self._r.headers.update({
            "User-Agent": self.USER_AGENT
        })

    def _check(self, response):
        if response.status_code == 200:
            data = response.json()
            return data
        elif response.status_code == 429:
            raise self.TooManyRequests("too many requests")
        elif 400 <= response.status_code <= 599:
            data = response.json()
            for i in data.get("warnings", []):
                print(i, file=sys.stderr)
            print(data["details"], file=sys.stderr)
            raise self.APIError("API returned status code " + str(response.status_code))
        else:
            raise APIError("Unknown error (status code: " + str(response.status_code))

    def _get_url(self, url, params=None):
        if params is None:
            params = {}

        return self._check(
            self._r.get(url, params=params)
        )

    def _get(self, api, params=None):
        if params is None:
            params = {}

        return self._check(
            self._r.get(self.API_URL + api, params=params)
        )

    def search(self, q, order):
        data = self._get("/cards/search", params={"q": q, "order": order})

        yield from (ScryfallCard(card, **self.card_kwargs) for card in data["data"])

        more = data.get("has_more", False)
        next_page = data.get("next_page", None)
        while more and next_page:
            time.sleep(self.SLEEP)
            data = self._get_url(next_page)
            more = data.get("has_more", False)
            next_page = data.get("next_page", None)
            yield from (ScryfallCard(card, **self.card_kwargs) for card in data["data"])

    def named(self, name, exact=False):
        params = {"fuzzy": name}
        if exact:
            params = {"exact": name}

        return ScryfallCard(self._get("/cards/named", params=params), **self.card_kwargs)

    def random(self, count=1):
        for _ in range(count):
            yield ScryfallCard(self._get("/cards/random"), **self.card_kwargs)
            time.sleep(self.SLEEP)

    def sets(self, set_code):
        api = "/sets"
        if set_code is not None:
            api += "/" + set_code
        data = self._get(api)
        if set_code is None:
            yield from (ScryfallSet(i) for i in data["data"])
            more = data.get("has_more", False)
            next_page = data.get("next_page", None)
            while more and next_page:
                time.sleep(self.SLEEP)
                data = self._get_url(next_page)
                more = data.get("has_more", False)
                next_page = data.get("next_page", None)
                yield from (ScryfallSet(i) for i in data["data"])
        else:
            yield ScryfallSet(data)

    def catalog(self, what):
        return self._get("/catalog/" + what)["data"]


text:
from __future__ import absolute_import, division, print_function, unicode_literals

import functools
import os
import re

from pants.backend.jvm.subsystems.jvm_tool_mixin import JvmToolMixin
from pants.backend.jvm.tasks.coverage.engine import CoverageEngine
from pants.base.exceptions import TaskError
from pants.java.jar.jar_dependency import JarDependency
from pants.subsystem.subsystem import Subsystem
from pants.util.dirutil import safe_mkdir, safe_walk

class Jacoco(CoverageEngine):
  """Class to run coverage tests with Jacoco."""

  class Factory(Subsystem, JvmToolMixin):
    options_scope = 'jacoco'

    @classmethod
    def register_options(cls, register):
      super(Jacoco.Factory, cls).register_options(register)

      def jacoco_jar(name, **kwargs):
        return JarDependency(org='org.jacoco', name=name, rev='0.8.0', **kwargs)

      # We need to inject the jacoco agent at test runtime
      cls.register_jvm_tool(register,
                            'jacoco-agent',
                            classpath=[
                              jacoco_jar(name='org.jacoco.agent', classifier='runtime')
                            ])

      # We'll use the jacoco-cli to generate reports
      cls.register_jvm_tool(register,
                            'jacoco-cli',
                            classpath=[
                              jacoco_jar(name='org.jacoco.cli')
                            ])

      register('--target-filters', type=list, default=[],
          help='Regex patterns passed to jacoco, specifying which targets should be '
              'included in reports. All targets matching any of the patterns will be '
              'included when generating reports. If no targets are specified, all '
              'targets are included, which would be the same as specifying ".*" as a '
              'filter.')

    def create(self, settings, targets, execute_java_for_targets):
      """
      :param settings: Generic code coverage settings.
      :type settings: :class:`CodeCoverageSettings`
      :param list targets: A list of targets to instrument and record code coverage for.
      :param execute_java_for_targets: A function that accepts a list of targets whose JVM platform
                                       constraints are used to pick a JVM `Distribution`. The
                                       function should also accept `*args` and `**kwargs` compatible
                                       with the remaining parameters accepted by
                                       `pants.java.util.execute_java`.
      """

      agent_path = self.tool_jar_from_products(settings.context.products, 'jacoco-agent',
                                               scope='jacoco')
      cli_path = self.tool_classpath_from_products(settings.context.products, 'jacoco-cli',
                                                   scope='jacoco')
      target_filters = Jacoco.Factory.global_instance().get_options().target_filters

      return Jacoco(settings, agent_path, cli_path, targets, target_filters, execute_java_for_targets)

  _DATAFILE_NAME = 'jacoco.exec'

  def __init__(self, settings, agent_path, cli_path, targets, target_filters, execute_java_for_targets):
    """
    :param settings: Generic code coverage settings.
    :type settings: :class:`CodeCoverageSettings`
    :param list targets: A list of targets to instrument and record code coverage for.
    :param execute_java_for_targets: A function that accepts a list of targets whose JVM platform
                                     constraints are used to pick a JVM `Distribution`. The function
                                     should also accept `*args` and `**kwargs` compatible with the
                                     remaining parameters accepted by
                                     `pants.java.util.execute_java`.
    """
    self._settings = settings
    options = settings.options
    self._context = settings.context
    self._targets = targets
    self._target_filters = target_filters
    self._coverage_targets = self._get_jacoco_coverage_targets(targets)
    self._agent_path = agent_path
    self._cli_path = cli_path
    self._execute_java = functools.partial(execute_java_for_targets, targets)
    self._coverage_force = options.coverage_force

  def _iter_datafiles(self, output_dir):
    for root, _, files in safe_walk(output_dir):
      for f in files:
        if f == self._DATAFILE_NAME:
          yield os.path.join(root, f)
          break

  def instrument(self, output_dir):
    # Since jacoco does runtime instrumentation, we only need to clean-up existing runs.
    for datafile in self._iter_datafiles(output_dir):
      os.unlink(datafile)

  def run_modifications(self, output_dir):
    datafile = os.path.join(output_dir, self._DATAFILE_NAME)
    agent_option = '-javaagent:{agent}=destfile={destfile}'.format(agent=self._agent_path,
                                                                   destfile=datafile)
    return self.RunModifications.create(extra_jvm_options=[agent_option])

  def _execute_jacoco_cli(self, workunit_name, args):
    main = 'org.jacoco.cli.internal.Main'
    result = self._execute_java(classpath=self._cli_path,
                                main=main,
                                jvm_options=self._settings.coverage_jvm_options,
                                args=args,
                                workunit_factory=self._context.new_workunit,
                                workunit_name=workunit_name)
    if result != 0:
      raise TaskError('java {} ... exited non-zero ({}) - failed to {}'
                      .format(main, result, workunit_name))

  def report(self, output_dir, execution_failed_exception=None):
    if execution_failed_exception:
      self._settings.log.warn('Test failed: {}'.format(execution_failed_exception))
      if self._coverage_force:
        self._settings.log.warn('Generating report even though tests failed, because the'
                                'coverage-force flag is set.')
      else:
        return

    report_dir = os.path.join(output_dir, 'coverage', 'reports')
    safe_mkdir(report_dir, clean=True)

    datafiles = list(self._iter_datafiles(output_dir))
    if len(datafiles) == 1:
      datafile = datafiles[0]
    else:
      datafile = os.path.join(output_dir, '{}.merged'.format(self._DATAFILE_NAME))
      args = ['merge'] + datafiles + ['--destfile={}'.format(datafile)]
      self._execute_jacoco_cli(workunit_name='jacoco-merge', args=args)

    for report_format in ('xml', 'csv', 'html'):
      target_path = os.path.join(report_dir, report_format)
      args = (['report', datafile] +
              self._get_target_classpaths() +
              self._get_source_roots() +
              ['--{report_format}={target_path}'.format(report_format=report_format,
                                                        target_path=target_path)])
      self._execute_jacoco_cli(workunit_name='jacoco-report-' + report_format, args=args)

    if self._settings.coverage_open:
      return os.path.join(report_dir, 'html', 'index.html')

  def _get_jacoco_coverage_targets(self, targets):
    coverage_targets = {t for t in targets if (self.is_coverage_target(t) and self._include_target(t))}
    if len(coverage_targets) == 0:
      raise TaskError("No coverage target specs matched jacoco report filters ({0})".format(self._target_filters))
    return coverage_targets

  def _get_target_classpaths(self):
    runtime_classpath = self._context.products.get_data('runtime_classpath')

    target_paths = []
    for target in self._coverage_targets:
      paths = runtime_classpath.get_for_target(target)
      for (name, path) in paths:
        target_paths.append(path)

    return self._make_multiple_arg('--classfiles', target_paths)

  def _include_target(self, target):
    if len(self._target_filters) == 0:
      return True
    else:
      for filter in self._target_filters:
        if re.search(filter, target.address.spec) is not None:
          return True
    return False

  def _get_source_roots(self):
    source_roots = {t.target_base for t in self._coverage_targets}
    return self._make_multiple_arg('--sourcefiles', source_roots)

  def _make_multiple_arg(self, arg_name, arg_list):
    """Jacoco cli allows the specification of multiple values for certain args by repeating the
    argument with a new value. E.g. --classfiles a.class --classfiles b.class, etc. This method
    creates a list of strings interleaved with the arg name to satisfy that format.
    """
    unique_args = list(set(arg_list))

    args = [(arg_name, f) for f in unique_args]
    flattened = list(sum(args, ()))

    return flattened


text:
cask 'cleanmymac' do
  version '3.9.2,1511452115'
  sha256 'e8845b55c50a444db1f0456f8b8a97b10cf8a1552378ec7b09de882634969ff2'

  # devmate.com/com.macpaw.CleanMyMac was verified as official when first introduced to the cask
  url "https://dl.devmate.com/com.macpaw.CleanMyMac#{version.major}/#{version.major_minor_patch}/#{version.after_comma}/CleanMyMac3-#{version.major_minor_patch}.zip"
  appcast "https://updates.devmate.com/com.macpaw.CleanMyMac#{version.major}.xml",
          checkpoint: 'f6eecaffbe7804993fbdffc2702f84ba50939c45d89559a2ac87a6329c78ab8c'
  name 'CleanMyMac'
  homepage 'https://macpaw.com/cleanmymac'

  app "CleanMyMac #{version.major}.app"

  uninstall delete:     "/Library/PrivilegedHelperTools/com.macpaw.CleanMyMac#{version.major}.Agent",
            launchctl:  [
                          "com.macpaw.CleanMyMac#{version.major}.Agent",
                          "com.macpaw.CleanMyMac#{version.major}.Scheduler",
                        ],
            login_item: "CleanMyMac #{version.major} Menu",
            quit:       [
                          "com.macpaw.CleanMyMac#{version.major}",
                          "com.macpaw.CleanMyMac#{version.major}.Menu",
                        ]

  zap trash: [
               "/private/var/run/com.macpaw.CleanMyMac#{version.major}.Agent.socket",
               "/Users/Shared/CleanMyMac #{version.major}",
               "/Users/Shared/CleanMyMac #{version.major} Menu",
               "~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.macpaw.cleanmymac#{version.major}.sfl*",
               "~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.macpaw.cleanmymac#{version.major}.scheduler.sfl*",
               "~/Library/Application Support/CleanMyMac #{version.major}",
               "~/Library/Application Support/CleanMyMac #{version.major} Menu",
               "~/Library/Caches/CleanMyMac #{version.major}",
               "~/Library/Caches/com.apple.helpd/SDMHelpData/Other/English/HelpSDMIndexFile/com.macpaw.CleanMyMac#{version.major}.help*",
               "~/Library/Caches/com.macpaw.CleanMyMac#{version.major}",
               "~/Library/Caches/com.macpaw.CleanMyMac#{version.major}.KnowledgeBase",
               "~/Library/Caches/com.macpaw.CleanMyMac#{version.major}.Menu",
               "~/Library/Caches/com.macpaw.CleanMyMac#{version.major}.Scheduler",
               "~/Library/Logs/CleanMyMac #{version.major}.log",
               "~/Library/Logs/com.macpaw.CleanMyMac#{version.major}",
               "~/Library/Preferences/com.macpaw.CleanMyMac-#{version.major}-Helper.plist",
               "~/Library/Preferences/com.macpaw.CleanMyMac#{version.major}.KnowledgeBase.plist",
               "~/Library/Preferences/com.macpaw.cleanmymac#{version.major}.menu.plist",
               "~/Library/Preferences/com.macpaw.CleanMyMac#{version.major}.Scheduler.plist",
               "~/Library/Preferences/com.macpaw.CleanMyMac#{version.major}.plist",
               "~/Pictures/Photos Library.photoslibrary/private/com.macpaw.CleanMyMac#{version.major}",
             ]
end


text:
require_relative "abstract_unit"

module ActiveSupport
  class BroadcastLoggerTest < TestCase
    attr_reader :logger, :log1, :log2

    setup do
      @log1 = FakeLogger.new
      @log2 = FakeLogger.new
      @log1.extend Logger.broadcast @log2
      @logger = @log1
    end

    Logger::Severity.constants.each do |level_name|
      method = level_name.downcase
      level = Logger::Severity.const_get(level_name)

      test "##{method} adds the message to all loggers" do
        logger.public_send(method, "msg")

        assert_equal [level, "msg", nil], log1.adds.first
        assert_equal [level, "msg", nil], log2.adds.first
      end
    end

    test "#close broadcasts to all loggers" do
      logger.close

      assert log1.closed, "should be closed"
      assert log2.closed, "should be closed"
    end

    test "#<< shovels the value into all loggers" do
      logger << "foo"

      assert_equal %w{ foo }, log1.chevrons
      assert_equal %w{ foo }, log2.chevrons
    end

    test "#level= assigns the level to all loggers" do
      assert_equal ::Logger::DEBUG, logger.level
      logger.level = ::Logger::FATAL

      assert_equal ::Logger::FATAL, log1.level
      assert_equal ::Logger::FATAL, log2.level
    end

    test "#progname= assigns to all the loggers" do
      assert_nil logger.progname
      logger.progname = ::Logger::FATAL

      assert_equal ::Logger::FATAL, log1.progname
      assert_equal ::Logger::FATAL, log2.progname
    end

    test "#formatter= assigns to all the loggers" do
      assert_nil logger.formatter
      logger.formatter = ::Logger::FATAL

      assert_equal ::Logger::FATAL, log1.formatter
      assert_equal ::Logger::FATAL, log2.formatter
    end

    test "#local_level= assigns the local_level to all loggers" do
      assert_equal ::Logger::DEBUG, logger.local_level
      logger.local_level = ::Logger::FATAL

      assert_equal ::Logger::FATAL, log1.local_level
      assert_equal ::Logger::FATAL, log2.local_level
    end

    test "#silence does not break custom loggers" do
      new_logger = FakeLogger.new
      custom_logger = CustomLogger.new
      assert_respond_to new_logger, :silence
      assert_not_respond_to custom_logger, :silence

      custom_logger.extend(Logger.broadcast(new_logger))

      custom_logger.silence do
        custom_logger.error "from error"
        custom_logger.unknown "from unknown"
      end

      assert_equal [[::Logger::ERROR, "from error", nil], [::Logger::UNKNOWN, "from unknown", nil]], custom_logger.adds
      assert_equal [[::Logger::ERROR, "from error", nil], [::Logger::UNKNOWN, "from unknown", nil]], new_logger.adds
    end

    test "#silence silences all loggers below the default level of ERROR" do
      logger.silence do
        logger.debug "test"
      end

      assert_equal [], log1.adds
      assert_equal [], log2.adds
    end

    test "#silence does not silence at or above ERROR" do
      logger.silence do
        logger.error "from error"
        logger.unknown "from unknown"
      end

      assert_equal [[::Logger::ERROR, "from error", nil], [::Logger::UNKNOWN, "from unknown", nil]], log1.adds
      assert_equal [[::Logger::ERROR, "from error", nil], [::Logger::UNKNOWN, "from unknown", nil]], log2.adds
    end

    test "#silence allows you to override the silence level" do
      logger.silence(::Logger::FATAL) do
        logger.error "unseen"
        logger.fatal "seen"
      end

      assert_equal [[::Logger::FATAL, "seen", nil]], log1.adds
      assert_equal [[::Logger::FATAL, "seen", nil]], log2.adds
    end

    class CustomLogger
      attr_reader :adds, :closed, :chevrons
      attr_accessor :level, :progname, :formatter, :local_level

      def initialize
        @adds        = []
        @closed      = false
        @chevrons    = []
        @level       = ::Logger::DEBUG
        @local_level = ::Logger::DEBUG
        @progname    = nil
        @formatter   = nil
      end

      def debug(message, &block)
        add(::Logger::DEBUG, message, &block)
      end

      def info(message, &block)
        add(::Logger::INFO, message, &block)
      end

      def warn(message, &block)
        add(::Logger::WARN, message, &block)
      end

      def error(message, &block)
        add(::Logger::ERROR, message, &block)
      end

      def fatal(message, &block)
        add(::Logger::FATAL, message, &block)
      end

      def unknown(message, &block)
        add(::Logger::UNKNOWN, message, &block)
      end

      def <<(x)
        @chevrons << x
      end

      def add(message_level, message = nil, progname = nil, &block)
        @adds << [message_level, message, progname] if message_level >= local_level
      end

      def close
        @closed = true
      end
    end

    class FakeLogger < CustomLogger
      include ActiveSupport::LoggerSilence

      # LoggerSilence includes LoggerThreadSafeLevel which defines these as
      # methods, so we need to redefine them
      attr_accessor :level, :local_level
    end
  end
end


text:
package com.hp.hpl.jena.util;

import java.util.*;
import java.io.*;
import com.hp.hpl.jena.vocabulary.*;
import com.hp.hpl.jena.datatypes.xsd.XSDDatatype;
import com.hp.hpl.jena.graph.*;
import com.hp.hpl.jena.rdf.model.*;
import com.hp.hpl.jena.reasoner.TriplePattern;
import com.hp.hpl.jena.shared.PrefixMapping;

/**
 * A collection of small utilites for pretty printing nodes, triples
 * and associated things. The core functionality here is a static
 * prefix map which is preloaded with known prefixes.
 *
 *
updated by Chris March 2004 to use a PrefixMapping rather than the
 * specialised tables.
 *
 * @author Dave Reynolds
 * @version $Revision: 1.1 $ on $Date: 2009-06-29 08:55:47 $
 */
public class PrintUtil {

    protected static PrefixMapping prefixMapping = PrefixMapping.Factory.create();

    /** Default built in eg namespace used in testing */
    public static final String egNS = "urn:x-hp:eg/";

    static {
        init();
    }

    /**
     * Load built in prefixes.
     */
    public static void init() {
        registerPrefix("rdf", RDF.getURI());
        registerPrefix("rdfs", RDFS.getURI());
        registerPrefix("drdfs", "urn:x-hp-direct-predicate:http_//www.w3.org/2000/01/rdf-schema#");
        registerPrefix("owl", OWL.getURI());
        registerPrefix("daml", DAML_OIL.NAMESPACE_DAML.getURI());
        registerPrefix("jr", ReasonerVocabulary.getJenaReasonerNS());
        registerPrefix("rb", ReasonerVocabulary.getRBNamespace());
        registerPrefix("eg", egNS);
        registerPrefix("xsd", XSDDatatype.XSD + "#");
    }

    /**
     * Register a new prefix/namespace mapping which will be used to shorten
     * the print strings for resources in known namespaces.
     */
    public static void registerPrefix(String prefix, String namespace) {
        prefixMapping.setNsPrefix( prefix, namespace );
    }

    /**
     * Register a set of new prefix/namespace mapping which will be used to shorten
     * the print strings for resources in known namespaces.
     */
    public static void registerPrefixMap(Map<String, String> map) {
        prefixMapping.setNsPrefixes( map );
    }

    /**
     * Remove a registered prefix from the table of known short forms
     */
    public static void removePrefix(String prefix) {
        prefixMapping.removeNsPrefix(prefix);
    }

    /**
     * Remove a set of prefix mappings from the table of known short forms
     */
    public static void removePrefixMap(Map<String, String> map) {
        for(Iterator<String> i = map.keySet().iterator(); i.hasNext(); ) {
            prefixMapping.removeNsPrefix( i.next() );
        }
    }

    /**
     * Return a simplified print string for a Node.
     */
    public static String print(Node node) {
        if (node instanceof Node_URI) {
            return node.toString( prefixMapping );
        } else if (node instanceof Node_Literal) {
            String lf = node.getLiteralLexicalForm();
            return "'" + lf + "'" + (node.getLiteralDatatype() == null ? "" : "^^" + node.getLiteralDatatypeURI());
        } else if (node instanceof Node_ANY) {
            return "*";
        }
        if (node == null) {
            return "null";
        }
        return node.toString();
    }

    /**
     * Return a simplified print string for an RDFNode.
     */
    public static String print(RDFNode node) {
        if (node == null) return "null";
        return print(node.asNode());
    }

    /**
     * Return a simplified print string for a Triple
     */
    public static String print(Triple triple) {
        if (triple == null) return "(null)";
        return "(" + print(triple.getSubject()) + " " +
                      print(triple.getPredicate()) + " " +
                      print(triple.getObject()) + ")";
    }

    /**
     * Return a simplified print string for a TriplePattern
     */
    public static String print(TriplePattern triple) {
        if (triple == null) return "(null)";
        return "(" + print(triple.getSubject()) + " " +
                      print(triple.getPredicate()) + " " +
                      print(triple.getObject()) + ")";
    }

    /**
     * Return a simplified print string for a statment
     */
    public static String print(Statement stmt) {
        if (stmt == null) return "(null)";
        return print(stmt.asTriple());
    }

    /**
     * Default print which just uses tostring
     */
    public static String print(Object obj) {
        if (obj == null) return "null";
        if (obj instanceof Triple) {
            return print((Triple)obj);
        } else if (obj instanceof TriplePattern) {
            return print((TriplePattern)obj);
        } else if (obj instanceof Node) {
            return print((Node)obj);
        } else if (obj instanceof RDFNode) {
            return print((RDFNode)obj);
        } else if (obj instanceof Statement) {
            return print((Statement)obj);
        } else {
            return obj.toString();
        }
    }

    /**
     * Expand qnames to URIs. If the given URI appears
     * to start with one of the registered prefixes then
     * expand the prefix, otherwise return the original URI
     */
    public static String expandQname(String uri) {
        return prefixMapping.expandPrefix( uri );
    }

    /**
     * Print an n-space indent to the given output stream
     */
    public static void printIndent(PrintWriter out, int indent) {
        StringBuffer spaces = new StringBuffer();
        for (int i = 0; i < indent; i++) spaces.append(" ");
        out.print(spaces.toString());
    }

    /**
     * Print all the Triple values from a find iterator.
     */
    public static void printOut( Iterator<?> it ) {
        while (it.hasNext()) {
            System.out.println("   " + print(it.next()));
        }
    }
}


text:
package io.crate.plugin;

import io.crate.module.CrateMonitoringModule;
import org.elasticsearch.common.inject.Module;
import org.elasticsearch.plugins.Plugin;

import java.util.Collection;
import java.util.List;

public class CrateMonitoringPlugin extends Plugin {

    @Override
    public Collection<Module> createGuiceModules() {
        return List.of(new CrateMonitoringModule());
    }
}


text:
namespace mimosa
{
  namespace http
  {
    template class MessageReader<ClientChannel, Response>;
  }
}


text:
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.codeInspection.noReturnMethod;

import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.codeInspection.GroovyInspectionBundle;
import org.jetbrains.plugins.groovy.codeInspection.GroovySuppressableInspectionTool;
import org.jetbrains.plugins.groovy.codeInspection.utils.ControlFlowUtils;
import org.jetbrains.plugins.groovy.lang.psi.GrControlFlowOwner;
import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementVisitor;
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrCodeBlock;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrOpenBlock;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrReturnStatement;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod;
import org.jetbrains.plugins.groovy.lang.psi.controlFlow.Instruction;
import org.jetbrains.plugins.groovy.lang.psi.controlFlow.impl.MaybeReturnInstruction;
import org.jetbrains.plugins.groovy.lang.psi.controlFlow.impl.ThrowingInstruction;
import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.GroovyExpectedTypesProvider;
import org.jetbrains.plugins.groovy.lang.psi.impl.signatures.GrClosureSignatureUtil;
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author ven
 */
public class MissingReturnInspection extends GroovySuppressableInspectionTool {

  @Override
  @Nls
  @NotNull
  public String getDisplayName() {
    return GroovyInspectionBundle.message("no.return.display.name");
  }

  public enum ReturnStatus {
    mustReturnValue, shouldReturnValue, shouldNotReturnValue;

    public static ReturnStatus getReturnStatus(PsiElement subject) {
      if (subject instanceof GrClosableBlock) {
        final PsiType inferredReturnType = getExpectedClosureReturnType((GrClosableBlock)subject);
        if (inferredReturnType instanceof PsiClassType) {
          PsiClass resolved = ((PsiClassType)inferredReturnType).resolve();
          if (resolved != null && !(resolved instanceof PsiTypeParameter)) return mustReturnValue;
        }
        return inferredReturnType != null && !PsiType.VOID.equals(inferredReturnType) ? shouldReturnValue : shouldNotReturnValue;
      }
      else if (subject instanceof GrMethod) {
        return ((GrMethod)subject).getReturnTypeElementGroovy() != null && !PsiType.VOID.equals(((GrMethod)subject).getReturnType())
               ? mustReturnValue
               : shouldNotReturnValue;
      }
      return shouldNotReturnValue;
    }
  }

  @Nullable
  public static PsiType getExpectedClosureReturnType(GrClosableBlock closure) {
    List<PsiType> expectedReturnTypes = new ArrayList<>();

    PsiElement parent = closure.getParent();
    if (parent instanceof GrArgumentList && parent.getParent() instanceof GrMethodCall || parent instanceof GrMethodCall) {
      GrMethodCall call = (GrMethodCall)(parent instanceof GrArgumentList ? parent.getParent() : parent);

      GroovyResolveResult[] variants = call.getCallVariants(null);

      for (GroovyResolveResult variant : variants) {
        Map<GrExpression,Pair<PsiParameter,PsiType>> map =
          GrClosureSignatureUtil.mapArgumentsToParameters(variant, closure, true, true, call.getNamedArguments(), call.getExpressionArguments(), call.getClosureArguments());

        if (map != null) {
          Pair<PsiParameter, PsiType> pair = map.get(closure);
          if (pair == null) continue;

          PsiParameter parameter = pair.getFirst();

          PsiType type = parameter.getType();
          if (TypesUtil.isPsiClassTypeToClosure(type)) {
            PsiType[] parameters = ((PsiClassType)type).getParameters();
            if (parameters.length == 1) {
              expectedReturnTypes.add(parameters[0]);
            }
          }
        }
      }
    }
    else {
      for (PsiType expectedType : GroovyExpectedTypesProvider.getDefaultExpectedTypes(closure)) {
        if (TypesUtil.isPsiClassTypeToClosure(expectedType)) {
          PsiType[] parameters = ((PsiClassType)expectedType).getParameters();
          if (parameters.length == 1) {
            expectedReturnTypes.add(parameters[0]);
          }
        }
      }
    }

    for (PsiType type : expectedReturnTypes) {
      if (type.equals(PsiType.VOID) || type.equals(PsiType.VOID.getBoxedType(closure))) return PsiType.VOID;
    }
    return TypesUtil.getLeastUpperBoundNullable(expectedReturnTypes, closure.getManager());
  }

  @Override
  @NotNull
  public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder problemsHolder, boolean onTheFly) {
    return new GroovyPsiElementVisitor(new GroovyElementVisitor() {
      @Override
      public void visitClosure(@NotNull GrClosableBlock closure) {
        super.visitClosure(closure);
        check(closure, problemsHolder, ReturnStatus.getReturnStatus(closure));
      }

      @Override
      public void visitMethod(@NotNull GrMethod method) {
        super.visitMethod(method);

        final GrOpenBlock block = method.getBlock();
        if (block != null) {
          check(block, problemsHolder, ReturnStatus.getReturnStatus(method));
        }
      }
    });
  }

  private static void check(GrCodeBlock block, ProblemsHolder holder, ReturnStatus returnStatus) {
    if (methodMissesSomeReturns(block, returnStatus)) {
      addNoReturnMessage(block, holder);
    }
  }

  public static boolean methodMissesSomeReturns(@NotNull GrControlFlowOwner block, @NotNull final ReturnStatus returnStatus) {
    if (returnStatus == ReturnStatus.shouldNotReturnValue) {
      return false;
    }

    final Ref<Boolean> alwaysHaveReturn = new Ref<>(true);
    final Ref<Boolean> sometimesHaveReturn = new Ref<>(false);
    final Ref<Boolean> hasExplicitReturn = new Ref<>(false);
    ControlFlowUtils.visitAllExitPoints(block, new ControlFlowUtils.ExitPointVisitor() {
      @Override
      public boolean visitExitPoint(Instruction instruction, @Nullable GrExpression returnValue) {
        //don't modify sometimesHaveReturn  in this case:
        // def foo() {
        //   if (cond) throw new RuntimeException()
        // }
        if (instruction instanceof ThrowingInstruction) {
          if (returnStatus == ReturnStatus.mustReturnValue) {
            sometimesHaveReturn.set(true);
          }
          return true;
        }

        if (instruction instanceof MaybeReturnInstruction && ((MaybeReturnInstruction)instruction).mayReturnValue()) {
          sometimesHaveReturn.set(true);
          return true;
        }

        if (instruction.getElement() instanceof GrReturnStatement && returnValue != null) {
          sometimesHaveReturn.set(true);
          hasExplicitReturn.set(true);
          return true;
        }

        alwaysHaveReturn.set(false);
        return true;
      }
    });

    if (returnStatus == ReturnStatus.mustReturnValue && !sometimesHaveReturn.get()) {
      return true;
    }

    return sometimesHaveReturn.get() && !alwaysHaveReturn.get();
  }

  private static void addNoReturnMessage(GrCodeBlock block, ProblemsHolder holder) {
    final PsiElement lastChild = block.getLastChild();
    if (lastChild == null) return;
    TextRange range = lastChild.getTextRange();
    if (!lastChild.isValid() || !lastChild.isPhysical() || range.getStartOffset() >= range.getEndOffset()) {
      return;
    }
    holder.registerProblem(lastChild, GroovyInspectionBundle.message("no.return.message"));
  }

  @Override
  @NonNls
  @NotNull
  public String getShortName() {
    return "GroovyMissingReturnStatement";
  }

  @Override
  public boolean isEnabledByDefault() {
    return true;
  }
}


text:
package net.engio.lab;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)
@Suite.SuiteClasses(value = {
LaboratoryTest.class,
ExecutionContextTest.class})
public class AllTests {
}


text:
// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.TokenAttributes;
using Lucene.Net.Util;

namespace Lucene.Net.Analysis.Payloads
{

    /// <summary>
    /// Makes the <see cref="Token.Type"/> a payload.
    /// <para/>
    /// Encodes the type using System.Text.Encoding.UTF8.GetBytes(string)
    /// </summary>
    public class TypeAsPayloadTokenFilter : TokenFilter
    {
        private readonly IPayloadAttribute payloadAtt;
        private readonly ITypeAttribute typeAtt;

        public TypeAsPayloadTokenFilter(TokenStream input)
            : base(input)
        {
            payloadAtt = AddAttribute<IPayloadAttribute>();
            typeAtt = AddAttribute<ITypeAttribute>();
        }

        public override sealed bool IncrementToken()
        {
            if (m_input.IncrementToken())
            {
                string type = typeAtt.Type;
                if (type != null && type.Length > 0)
                {
                    payloadAtt.Payload = new BytesRef(type);
                }
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}